Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store %%time values in a variable in Jupyter? [duplicate]

Tags:

python

jupyter

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.

like image 624
Caner Erden Avatar asked Oct 10 '18 11:10

Caner Erden


2 Answers

There's no way to store the result of the %time magic, but you can store the result of the %timeitmagic. 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]
like image 168
Dunes Avatar answered Oct 02 '22 03:10

Dunes


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.

like image 32
dheinz Avatar answered Oct 02 '22 02:10

dheinz