I would like to get the time spent on the cell execution in addition to the original output from cell.
To this end, I tried %%timeit -r1 -n1
but it doesn’t expose the variable defined within cell.
%%time
works for cell which only contains 1 statement.
In[1]: %%time 1 CPU times: user 4 µs, sys: 0 ns, total: 4 µs Wall time: 5.96 µs Out[1]: 1 In[2]: %%time # Notice there is no out result in this case. x = 1 x CPU times: user 3 µs, sys: 0 ns, total: 3 µs Wall time: 5.96 µs
What’s the best way to do it?
Update
I have been using Execute Time in Nbextension for quite some time now. It is great.
Update 2021-03
As of now, this is the correct answer. Essentially, %%time
and %%timeit
both now work as one would expect.
Advertisement
Answer
That was only a problem in old versions.
All you need to do now is put %%time
at the top of the cell.
%%time
measures how long it took something to run. It’s better for reporting on long-running operations than for doing low-level optimization.
%%timeit
is a benchmarking tool that runs statements over and over to give the average runtime for some statements, as well as the standard deviation. Because of the way in which the statements are repeatedly executed, the variables created in %%timeit
cells are not available in other cells.
%%timeit
uses the python timeit
module. The docs for that say,
It avoids a number of common traps for measuring execution times. See also Tim Peters’ introduction to the “Algorithms” chapter in the Python Cookbook, published by O’Reilly.
I hope that that module is still relevant, as the reference it refers to describes issues such as (1) workarounds for Windows 98 only updating time.time()
18.2 times per second, and (2) jamming all the statements onto one line to avoid the bytecode overhead of incrementing the line number counter.
The currently top-rated answer, as well as some of the other outdated ones—which should be deleted because they are now highly misleading—do have useful comments indicating that those answers are not correct: