# Timing evaluation times dynamically

I am wanting to make a function that times how long an evaluation takes to run dynamically, with the effect similar to if I were to use an online stopwatch and started it when I hit run. If the evaluation took 10 s i could watch the timer count up to that time. Any help? Ive tried to make my own already with various combinations of dynamic and timing, but have been unsuccessful.

• Absolute Timing captures the stopwatch-like time effect, but you will probably need to parallelize in order to visually see the timer. Otherwise the kernel finishes the entire evaluation before updating the dynamic content. – Bill Molchan Dec 9 '16 at 21:02

I would use Clock with PrintTemporary to run a timer and AbsoluteTiming to report the computation time. The following is quite easy to code on the fly when needed:

PrintTemporary@ Dynamic@ Clock[Infinity];
Sum[Pause[1]; i, {i, 3}] // AbsoluteTiming


Used this way, the clock runs completely in the Front End and shouldn't slow down the kernel at all in a multi-core, multi-threaded environment. The timer is visible until the evaluation is completed, at which point it is replaced by the results of AbsoluteTiming and the computation.

• I don't know why it needs to it calls the Kernel to get that value. – Kuba May 9 '17 at 15:39
• @Kuba What value? I think Clock[] runs completely in the FE. t = Clock[..] would call the Kernel to store t (unless t was a DynamicModule variable). Is that what you're talking about? – Michael E2 May 9 '17 at 16:38
• I mean that with LinkSnooper one can see that it is calling the Kernel. – Kuba May 9 '17 at 16:40
• @Kuba Darn. I thought it didn't. I think my LinkSnooper is broken. It seems to break whenever I upgrade and I forget what I had to do to get it to work. Oh well, maybe I'll try to fix it. Thanks. – Michael E2 May 9 '17 at 16:43
• @Kuba Maybe it's calling the kernel b/c of Infinity. – Michael E2 Mar 27 '18 at 21:25

A very simple prototype:

Clear[stop, stopwatch];
stopwatch[b_] := If[b == 1, startTime = Now; stop = 0;
Dynamic[tracker = If[stop != 1, Clock[]];
Now - startTime,TrackedSymbols :> {tracker}], stop = 1;]


Testing:

stopwatch[1]
Integrate[Product[Sin[x/(2 k + 1)], {k, 0, 8}]/x^9, {x, 0, Infinity}] // AbsoluteTiming // First
stopwatch[0]

(* Dynamic object, stops at 10.908s
10.8757  *)


So, there is a little bit of overhead associated with function call, but roughly you get the timing right.

• That does what I want. I'll leave the question open for a bit, to see if anything else comes along, but thank you – Brandon Myers Dec 10 '16 at 21:59