       Timing runs for the last part of my previous post

• To: mathgroup at smc.vnet.net
• Subject: [mg62031] Timing runs for the last part of my previous post
• From: "Matt" <anonmous69 at netscape.net>
• Date: Wed, 9 Nov 2005 05:05:50 -0500 (EST)
• Sender: owner-wri-mathgroup at wolfram.com

```OK,
After I posted my earlier message (the one entitled "'Good' or
'Proper' Mathematica coding habits question"), I decided to try some
timings for the last code sample I had a question on (the one trying to
extract all sublists where each element of a sublist had to be
negative).  Here's what I found:

This table was generated, then used for all the approaches:
values = Table[{Random[Real, {-2, 2}] i, Random[Real, {-2, 2}] i}, {i,
1, 2000}];

Approach #1:

ClearAll[testFuncOne];
testFuncOne[] := Module[{negElems = {}},
(If[Negative[#[]] &&
Negative[#[]], negElems = {negElems, #}]) & /@ values;
StandardForm[Partition[Flatten[negElems], 2]];
];

Approach #2:

ClearAll[testFuncTwo];
testFuncTwo[] := Module[{negElems = {}},
Fold[If[Negative[#2[]] && Negative[#2[]], negElems = {
negElems, #2}, negElems] &, values[], values];
StandardForm[Partition[Flatten[negElems], 2]];
];

Approach #3:

ClearAll[testFuncThree];
testFuncThree[] := Module[{negElems = {} , lengthOfValues =
Length[values], ii = 1},
While[ii = lengthOfValues,
If[
Negative[values[[ii]][]] &&
Negative[values[[ii]][]],
negElems = {negElems, values[[ii]]};
]
ii++;
];
StandardForm[Partition[Flatten[negElems], 2]];
];

And the test run was:

Timing[Do[testFuncOne[], {10^3}]][]
Timing[Do[testFuncTwo[], {10^3}]][]
Timing[Do[testFuncThree[], {10^3}]][]

The results obtained were 13.625, 12.812, and 19.11 Seconds.  So, it
appears that of the methods I tried, that Approach 2 is marginally
better than Approach 1, and both Approach 1 and Approach 2 are better
than Approach 3.  Is it correct to assume from this that Fold will
almost always be better than Map, given that other potential variants
are kept similar?  Or, because the difference is so small, that for
most applications, I should go with whatever approach is quicker to
'code up'?

Thanks,

Matt

```

• Prev by Date: Re: ((a&&b)||c)==((a||c)&&(b||c))
• Next by Date: Re: Fitting numerical data
• Previous by thread: Timing runs for the last part of my previous post
• Next by thread: Re: Timing runs for the last part of my previous post