MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: four approaches to do a simple sum

  • To: mathgroup at smc.vnet.net
  • Subject: [mg57213] Re: [mg57171] four approaches to do a simple sum
  • From: "Caffa Vittorio Dr." <Caffa at iabg.de>
  • Date: Sat, 21 May 2005 02:39:26 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com


By the way:

Timing[Fold[Plus, 0, longlist]]
{0.22 Second, 499831.}

Timing[Total[longlist]]
{0.01 Second, 499831.}

Cheers, Vittorio


>-----Original Message-----
>From: Hui Fang [mailto:fangh73 at xmu.edu.cn]
To: mathgroup at smc.vnet.net
>Sent: Friday, May 20, 2005 10:43 AM
>Subject: [mg57213] [mg57171] four approaches to do a simple sum
>
>Here I have a long list, length of 1 million, and I used 4 ways to get
>the sum of all elements.
>
>In[1] = longlist=Table[Random[], {1000000}];
>
>Method 1:
>In[2] = Timing[sum=0; For[i=1,i<=Length[longlist],sum+=longlist[[i]]];
sum]
>Out[2] = {6.219 Second, 500358}
>
>Method 2:
>In[3] = Sum[longlist[[i]],{i,1,1000000}]
>Out[3] = {1.718 Second, 500358}
>
>Method 3:
>In[4] = Timing[Plus@@longlist]
>Out[4] = {0.407 Second, 500358}
>
>Method 4:
>In[5] = Fold[Plus,0,longlist]
>Out[5] = {0.156 Second, 500358}
>
>The computing time gets shorter and shorter from top to bottom. It's
>easy to understand why the first two methods are slow because they
>involved an extra variable i for loop control and basically violates
the
>principle for list manipulation "Never take a list apart".
>What I don't understand is why method 4 is faster than method 3.
>Any explanation?Or do you have an even faster method?
>Thanks a lot!
>
>Hui Fang


  • Prev by Date: Re: NonLinearRegress and constraint parameters
  • Next by Date: Re: Mathematica 5.1 and Oracle 10g
  • Previous by thread: Re: four approaches to do a simple sum
  • Next by thread: Re: four approaches to do a simple sum