I would like to know the CPU time of a cell working in Jupyter. I put %%time at the top of the cell. It prints out Wall time. But I couldn't store this time value in a variable?
Could you please help me on that?
Thanks.
There's no way to store the result of the %time
magic, but you can store the result of the %timeit
magic. The timeit
magic is a bit more configurable. So if you want it to behave exactly as %time
you need to configure it do so. In the following code the arguments -n1 -r1 and -o
are used. Here -n1
means run the code n (1) times in a loop. -r1
means run the loop r (1) times and take the best result. You don't need to use these flags, they just mean you will get a result quicker. If you do use them, then the result will be more representative though. The magic will try to pick sensible values for n
and r
depending on how quick or slow the timed code is. This means you should get a result in about the same time no matter how quick or fast your code is. As such you probably don't want to use them. Finally, -o
means return a result object (as opposed to just printing the results).
eg.
In [1]: result = %timeit -n1 -r1 -o sum(range(1000000))
53.7 ms ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
In [2]: print(result)
print(result.average)
53.7 ms ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
0.05373367803767323
The cell magic is a bit more complicated as you cannot directly assign its result.
In [1]: %%timeit -o
sum(range(1000000))
24.8 ms ± 1.18 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Out[1]: <TimeitResult : 24.8 ms ± 1.18 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)>
In [2]: result = _ # or result = Out[1]
You could also define your own function which receives a timestamp at the beginning and at the end of a cell. For example:
import time
def exec_time(start, end):
diff_time = end - start
m, s = divmod(diff_time, 60)
h, m = divmod(m, 60)
s,m,h = int(round(s, 0)), int(round(m, 0)), int(round(h, 0))
print("Execution Time: " + "{0:02d}:{1:02d}:{2:02d}".format(h, m, s))
and then run as follows:
start = time.time()
...
...
end = time.time()
exec_time(start,end)
This prints out exection time in a hh:mm:ss format.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With