Re: four approaches to do a simple sum

• To: mathgroup at smc.vnet.net
• Subject: [mg57212] Re: [mg57171] four approaches to do a simple sum
• From: Bob Hanlon <hanlonr at cox.net>
• Date: Sat, 21 May 2005 02:39:25 -0400 (EDT)
• Reply-to: hanlonr at cox.net
• Sender: owner-wri-mathgroup at wolfram.com

```I don't know the answer to your question but Tr is even faster.

longlist=Table[Random[],{1000000}];

Timing[Plus@@longlist]

{1.39 Second,499953.}

Timing[Fold[Plus,0,longlist]]

{0.53 Second,499953.}

Timing[Tr[longlist]]

{0.03 Second,499953.}

Bob Hanlon

>
> From: Hui Fang <fangh73 at xmu.edu.cn>
To: mathgroup at smc.vnet.net
> Date: 2005/05/20 Fri AM 04:43:04 EDT
> Subject: [mg57212] [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: Mathematica 5.1 and Oracle 10g
• Next by Date: Re: runs test for evaluation of model fit
• Previous by thread: Re: four approaches to do a simple sum
• Next by thread: Re: four approaches to do a simple sum