6

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.

Caner Erden
  • 556
  • 7
  • 7
  • 1
    https://stackoverflow.com/questions/41351041/how-to-store-the-result-from-timeit-cell-magic – Rahul Agarwal Oct 10 '18 at 11:04
  • 1
    This is not a duplicate of that question, that is answering a different question. This one is about storing the timing results into a python var, the other one is about storing the function return values while doing inline timing. – OldGeeksGuide Jul 30 '21 at 19:59

2 Answers2

9

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]
Dunes
  • 37,291
  • 7
  • 81
  • 97
4

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.

dheinz
  • 988
  • 10
  • 16