MathGroup Archive 2005

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

Search the Archive

Timing runs for the last part of my previous post

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

  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:

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

Approach #2:

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

Approach #3:

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

And the test run was:

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

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'?



  • 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