       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:=
n = 10^6;
d = Table[i, {i, n}];
fun[x_] := x;

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

Out=
{0.109 Second,Null}

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

Out=
{0.781 Second,Null}

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

Out=
{0.954 Second,Null}

In:=
Timing[fun /@ d; ]

Out=
{0.968 Second,Null}

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

Out=
{1.188 Second,Null}

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

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

Out=
{2.172 Second,Null}

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

Out=
{2.094 Second,Null}

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

Out=
{2.359 Second,Null}

In:=
Timing[fun2 /@ d; ]

Out=
{2.328 Second,Null}

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

Out=
{2.609 Second,Null}

In:=
\$Version

Out=
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