strange timing behavior - Mathematica Stack Exchange most recent 30 from mathematica.stackexchange.com 2019-09-19T16:12:40Z https://mathematica.stackexchange.com/feeds/question/55383 https://creativecommons.org/licenses/by-sa/4.0/rdf https://mathematica.stackexchange.com/q/55383 0 strange timing behavior Dimitris https://mathematica.stackexchange.com/users/16314 2014-07-20T14:10:10Z 2014-07-20T14:53:10Z <p>The following code is from a book about Mathematica.</p> <pre><code>colMean[col_, str_String] := col /. str :&gt; Mean[Cases[col, _?NumberQ]] ReplaceString[matrix_, str_String] := Transpose[Map[colMean[#, str] &amp;, Transpose[matrix]]] </code></pre> <p>Giving a matrix with numeric and string entries in a column it replaces the string entries by the mean average of the remaing numeric elements of the column. Here is a test of its efficiency.</p> <pre><code>With[{size = 1000}, mat = RandomReal[1, {size, size}]; rmat = ReplacePart[mat, RandomInteger[{1, size}, {size, 2}] :&gt; "non"]]; Timing[ReplaceString[rmat, "non"];] {3.296875, Null} </code></pre> <p>Here is the respective time performance that appears in the book: <strong>0.877081</strong></p> <p>So far everything sounds normal. The author may have a faster computer than mine. However, in order to check the efficiency of its code, the author compares it with the performance of some of the highly optimized built-in linear algebra functions.</p> <pre><code>mat = RandomReal[1, {1000, 1000}]; {Timing[Inverse[mat];], Timing[Det[mat];]} </code></pre> <p>The times are about, respectively, 0.4 and 0.14 sec.</p> <p>The strange thing, at least to me, is that my machine has the same time performance. In particular:</p> <pre><code> mat = RandomReal[1, {1000, 1000}]; {Timing[Inverse[mat];], Timing[Det[mat];]} {{0.453125, Null}, {0.093750, Null}} </code></pre> <p>So, here comes my first question:</p> <p>How is it possible to be such a big difference in the performance of the user-defined code and almost identical timings in the performances of relevant built-in functions? What issues affect the performance of such codes?</p> <p>My second query now.</p> <p>In order to increase the efficiency of <code>ReplaceString</code> I tried to use parallel computing.</p> <pre><code>Clear[ReplaceString] LaunchKernels[] ReplaceString[matrix_, str_String] := Transpose[ParallelMap[colMean[#, str] &amp;, Transpose[matrix]]] </code></pre> <p>Nevertheless, I did not get any change in the perfomance of the function <code>ReplaceString</code>.</p> <pre><code>In:= \$ProcessorCount Out= 4 </code></pre> <p>The machine on which this computation was performed has two processors on which Mathematica can run kernels. (Actually, my machine has two physical processors and two virtual ones and so \$ProcessorCount returns 4.)</p> <p>Why there is not an increase in the efficiency of the function? What am I missing here?</p>