Re: Timing of Table
- To: mathgroup at smc.vnet.net
- Subject: [mg43257] Re: Timing of Table
- From: Robert Knapp <rknapp at wolfram.com>
- Date: Sat, 23 Aug 2003 08:08:32 -0400 (EDT)
- Organization: Wolfram Research, Inc.
- References: <bi18ce$afl$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Mariusz Jankowski wrote:
> Dear Mathematica Users,
>
> Can someone explain the timing difference between the following two code
> samples. I am guessing it has to do with the auto-compiler, but even if I am
> correct, I would like to know more.
>
> Slow version:
>
> n=m=100;
> Timing[Do[Table[1,{i,1,n},{j,1,m}],{1000}];]
>
>
>
> Fast version:
>
> n=m=100;
>
> Timing[Do[Table[1,{i,1,n},Evaluate[{j,1,m}]],{1000}];]
>
> which is as fast as
>
> Timing[Do[Table[1,{i,1,100},{j,1,100}]],{1000}];]
>
> I also noticed that only the outermost iterator needs to be wrapped in
> Evaluate. Why(?)
>
>
>
> Thanks, Mariusz
>
>
Yes, Mariusz, the issue has completely to do with auto-compilation but is quite
subtle.
Table[1,{i,1,n},{j,1,m}] is basically equivalent to
Table[Table[1, {j, 1, m}], {i, 1, n}]
With the second form it is a bit easier to see why it cannot be autocompiled.
Each time the inner Table is done, m needs to be evaluated to determine what the
limit should be. So the issue boils down to why it needs to be evaluated *each*
time through the outer loop.
Before evaluation, m is just a symbol, so it could have any evaluation attached
to it, say for instance
m := 10 i
With this, the result of evaluating with only one i would obviously be wrong.
You might think it would be possible to evaluate with i unset and use that, but
there are cases where that would be incorrect. e.g.
m := If[NumberQ[i], 10 i , 0]
This is, of course, pathological, but it is not too difficult to construct real
cases which give incorrect or misleading values. It is most important that
Mathematica be consistent, so we cannot do this.
Thus, since m cannot be surely known except for specific values of i, there is
no way to autocompile the loop as a whole in a really efficient way. On the
other hand when you evaluate, or put literal numbers in, everything is known, so
compilation analysis can be done quite completely.
Rob Knapp
Wolfram Research