The following code is from a book about Mathematica.
colMean[col_, str_String] := col /. str :> Mean[Cases[col, _?NumberQ]]
ReplaceString[matrix_, str_String] :=
Transpose[Map[colMean[#, str] &, Transpose[matrix]]]
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.
With[{size = 1000}, mat = RandomReal[1, {size, size}];
rmat = ReplacePart[mat,
RandomInteger[{1, size}, {size, 2}] :> "non"]];
Timing[ReplaceString[rmat, "non"];]
{3.296875, Null}
Here is the respective time performance that appears in the book: 0.877081
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.
mat = RandomReal[1, {1000, 1000}];
{Timing[Inverse[mat];], Timing[Det[mat];]}
The times are about, respectively, 0.4 and 0.14 sec.
The strange thing, at least to me, is that my machine has the same time performance. In particular:
mat = RandomReal[1, {1000, 1000}];
{Timing[Inverse[mat];], Timing[Det[mat];]}
{{0.453125, Null}, {0.093750, Null}}
So, here comes my first question:
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?
My second query now.
In order to increase the efficiency of ReplaceString
I tried to use parallel computing.
Clear[ReplaceString]
LaunchKernels[]
ReplaceString[matrix_, str_String] :=
Transpose[ParallelMap[colMean[#, str] &, Transpose[matrix]]]
Nevertheless, I did not get any change in the perfomance of the function ReplaceString
.
In[6]:= $ProcessorCount
Out[6]= 4
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.)
Why there is not an increase in the efficiency of the function? What am I missing here?
AbsoluteTiming
. $\endgroup$