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 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 03:46:17 -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[#[[1]]] &&
      Negative[#[[2]]], negElems = {negElems, #}]) & /@ values;
      StandardForm[Partition[Flatten[negElems], 2]];
      ];

Approach #2:

ClearAll[testFuncTwo];
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:

ClearAll[testFuncThree];
testFuncThree[] := Module[{negElems = {} , lengthOfValues =
Length[values], ii = 1},
      While[ii = lengthOfValues,
        If[
              Negative[values[[ii]][[1]]] &&
Negative[values[[ii]][[2]]],
              negElems = {negElems, values[[ii]]};
              ]
            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'?

Thanks,

Matt



  • Prev by Date: Re: Bug in pattern parsing?
  • Next by Date: feature request: invert plot axes
  • Previous by thread: Re: Notation Package Precedence?
  • Next by thread: Timing runs for the last part of my previous post