Re: Tr[list] vs Plus@@list
- To: mathgroup at smc.vnet.net
- Subject: [mg73713] Re: Tr[list] vs Plus@@list
- From: David Bailey <dave at Remove_Thisdbailey.co.uk>
- Date: Mon, 26 Feb 2007 06:11:37 -0500 (EST)
- References: <errm51$8b9$1@smc.vnet.net>
dimitris wrote:
> Can somebody explain me the difference in timing performances
> between the settings Tr[list] and Plus@@list?
>
> Thanks a lot!
>
> In[1]:=
> lst[i_] := Table[Random[], {i}]
>
> In[2]:=
> {Timing[Tr[lst[10^4]]; ], Timing[Tr[lst[10^5]]; ],
> Timing[Tr[lst[10^6]]; ], Timing[Tr[lst[10^7]]; ]}
>
> Out[2]=
> {{0.*Second, Null}, {0.030999999999999972*Second, Null},
> {0.15600000000000003*Second, Null}, {2.0469999999999997*Second, Null}}
>
> In[3]:=
> {Timing[Plus @@ lst[10^4]; ], Timing[Plus @@ lst[10^5]; ], Timing[Plus
> @@ lst[10^6]; ], Timing[Plus @@ lst[10^7]; ]}
>
> Out[3]=
> {{0.*Second, Null}, {0.04700000000000015*Second, Null}, {0.484*Second,
> Null}, {4.922000000000001*Second, Null}}
>
>
First, as written much of the time is spent in your lst function
evaluating random numbers!
If you pre-evaluate your list you will find that Plus@@ looks much
worse! Although it is hard to be sure how Mathematica handles particular
cases, I suspect that Plus@@ invokes some code that actually constructs
a function call to Plus with 10^7 arguments before evaluating it. Tr
probably operates on its argument directly.
David Bailey
http://www.dbaileyconsultancy.co.uk