MathGroup Archive 2005

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

Search the Archive

Re: Timing of looping operators

  • To: mathgroup at smc.vnet.net
  • Subject: [mg62445] Re: Timing of looping operators
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
  • Date: Thu, 24 Nov 2005 06:33:45 -0500 (EST)
  • Organization: The Open University, Milton Keynes, UK
  • References: <dm1cum$jp7$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

dh wrote:
> Hello,
> The Mathematica gospel tells you that you should NOT use loops because 
> it is inefficient.
> Well consider the following examples and their times:
> 
> n=10^6;
> d=Table[i,{i,n}];
> fun[x_]:=x;
> 
> a)  Timing[fun & /@ d;]       needs 0.8 sec
> b)  Timing[Scan[fun, d]]      needs 1 second
> c)  Timing[Do[f[i], {i, n}];] needs 0.7 sec
                 ====
           must be fun[i]
> 
> a) applies the function and creates a new list. b) does not create a new 
> list -- but it is slower! And finally c) the loop is fastest!!!
> 
> If you change the function to: f[x_]:=x^2, the times are even more striking:
> 
> 0.8, 2.4, 0.7
> it seems like in a and c the function evaluation takes negliable time 
> compared to the loop construct, but not so in b.
> 
> has anybody an explanation???
> 
> Daniel
> 
Hi Daniel,

in (c) your function must be fun[i0 rather than f[i]. Here what I get in 
bot cases (identity and square): the loop is systematically the 
slowest... and pure functions are the fastest, which is no surprise 
according to Mathematica gospel :-)

In[1]:=
n = 10^6;
d = Table[i, {i, n}];
fun[x_] := x;

In[4]:=
Timing[(#1 & ) /@ d; ]

Out[4]=
{0.109 Second,Null}

In[5]:=
Timing[Scan[#1 & , d]; ]

Out[5]=
{0.781 Second,Null}

In[6]:=
Timing[Scan[fun, d]; ]

Out[6]=
{0.954 Second,Null}

In[7]:=
Timing[fun /@ d; ]

Out[7]=
{0.968 Second,Null}

In[8]:=
Timing[Do[fun[i], {i, n}]; ]

Out[8]=
{1.188 Second,Null}

In[9]:=
fun2[x_] := x^2;

In[10]:=
Timing[(#1^2 & ) /@ d; ]

Out[10]=
{2.172 Second,Null}

In[11]:=
Timing[Scan[#1^2 & , d]; ]

Out[11]=
{2.094 Second,Null}

In[12]:=
Timing[Scan[fun2, d]; ]

Out[12]=
{2.359 Second,Null}

In[13]:=
Timing[fun2 /@ d; ]

Out[13]=
{2.328 Second,Null}

In[14]:=
Timing[Do[fun2[i], {i, n}]; ]

Out[14]=
{2.609 Second,Null}

In[15]:=
$Version

Out[15]=
5.2 for Microsoft Windows (June 20, 2005)

Best regards,
/J.M.


  • Prev by Date: Re: Time needed for calculation
  • Next by Date: Re: permutations
  • Previous by thread: Re: Timing of looping operators
  • Next by thread: permutations