I did an experiment in which I calculated the same quantity two different ways to see which method was faster. To my surprise, the kernel time was different in different runs. In fact, which method was faster differed between runs. Why? I expected the kernel time to be exactly the same for the same task. Have I misunderstood something about Timing
or about kernel time?
In the code below, I calculated the 0-15th derivatives of g[x,v]. dgdv2
is calculated using the Do
loop that Mathematica wizards say to never use, while dgdv3
is calculated the loop-free expert-approved way. The last line just verifies that the results are identical. I did three runs and got inconsistent times.
As a side note, in a different Question I asked, some commentors were confused by the first line of this code, so here is a link about defining derivatives. Also as a side note, the "bad code" seems to have been faster 2 times out of 3.
But my question here is about the Timing
inconsistency. If anyone wants to discuss the relevant coding practice, I posted a different Question about that.
Derivative[q_, 1][y][x, v] =
D[(D[y[x, v], {x, 2}] + D[y[x, v], x]^2), {x, q}]/2;
ord = 16;
Print[Timing[
dgdv2 = Flatten[{y[x, v], Table[0, {i, 2, ord}]}];
Do[dgdv2[[i]] = Expand[D[dgdv2[[i - 1]], v]], {i, 2, ord}];]];
Print[Timing[dgdv3 = NestList[Expand[D[#, v]] &, y[x, v], ord - 1];]];
dgdv2 == dgdv3
Output from 3 runs:
(*
{25.584164,Null}
{25.006960,Null}
True
{24.226955,Null}
{24.336156,Null}
True
{24.211355,Null}
{24.601358,Null}
True
*)
RepeatedTiming[]
. $\endgroup$Timing
fluctuates, given that it measures kernel time and not wall time? I don't know, but I guess it's not surprising ... e.g. CPUs can adjust their clock rate to reduce power consumption and avoid overheating. Maybe that's one factor. And most likely the measurement is not entirely precise anyway ... $\endgroup$Do
: there are plenty of good uses forDo
. I do sometimes say never ever to useFor
, but that's because of the many shortcomings ofFor
and doesn't apply toDo
or to procedural programming in general. There are many times better ways thanDo
but not always. $\endgroup$