Re: timing of Table operation
- To: mathgroup at yoda.physics.unc.edu
- Subject: Re: timing of Table operation
- From: TODD GAYLEY <TGAYLEY at ccit.arizona.edu>
- Date: Mon, 10 Aug 1992 01:15 MST
Jeff MacKie-Mason (jmm at umich.edu) asked about the explanation
for timing differences between two versions of Table-generating
code:
> In[2]:= rdist = NormalDistribution[(1.1^(1/240)-1),(0.2/240)]
>
> Out[2]= NormalDistribution[0.000397205, 0.000833333]
>
> In[3]:= annualReturns=Timing[Table[
> (Product[
> (1+Table[Random[rdist],{240}][[i]]),
> {i,1,240}
> ] - 1),
> {1}
> ]]
>
> Out[3]= {312.933 Second, {0.109928}}
>
> In[4]:= y = Timing[Table[Random[rdist],{240}]][[2]]
>
> Out[4]= {-0.000684265, < list of 240 numbers suppressed> }
>
> In[5]:= Timing[Product[(1+y[[i]]),{i,1,240}]-1]
>
> Out[5]= {0.266667 Second, 0.114892}
>
> So, the nested Tables took 5 minutes, the direct (two-step)
> approach less than 0.3 seconds.
Don't forget that Product is a looping construct as well. In the
nested version, the Table[Random[rdist],{240}] is executed 240
times! In other words, 240 separate tables of random numbers are
generated, and one number (the i'th) is picked from each for the
accumulating Product. This is just the classic optimization of taking
invariant code (the Table) out of a loop.
--Todd Gayley
--University of Arizona