I have a collection of functions (Modules) and I wish to find out which sub-routines inside the code take up most time. I have done this by wrapping individual code blocks with
Print[Row[{"comment: ", AbsoluteTiming[ --- code --- ]}]];
This is tedious to do, and it is also tedious to remove these code blocks again once I am done with my optimization.
What I am looking for is a routine that can be turned on and off (e.g. by setting an Option), something like
timeIt[ --- code --- ,"comment"];
that can be left in place - it will simply execute the code when the Option is set to not report timing, and it will execute the code and return the timings when it is turned on.
So far, when I tried to put my Print[...]
construct into an external module it worked, but it always returned a time of 0.
Here is the code that I have tried:
Clear[timeIt];
Options[timeIt] = {debugTiming -> True};
SetAttributes[timeIt, HoldFirst];
timeIt[f_, comment_: "", OptionsPattern[]] :=
If[OptionValue[debugTiming] === True,
Print @ Row[{comment,": ",First@AbsoluteTiming[ReleaseHold@f]}],
ReleaseHold@f];
Any suggestions of how to do this properly?
timeIt
? Are you requesting a code review? The first thing I note is that you do not needReleaseHold
as there is no actualHold
imposed by the use ofHoldFirst
. $\endgroup$SetAttributes[fn, HoldFirst]
and thenfn[x_] := AbsoluteTiming[x]
as the argument offn
will be passed unevaluated toAbsoluteTiming
and then evaluated normally; you do not need an additional release. Again I ask: are you having any functional problems with your implementation? $\endgroup$