Measure runtime of a Jupyter Notebook code cell
For basic timing functionality use the %%time
cell magic at the beginning of the cell.
%%timeit
allows for some more meaningful timing experiments by repeating the measurements. You can use the default options or define your own, for instance here's three runs with 100 loops each:
%%timeit -n100 -r3
import math; n = 2 # the first line is the setup and doesn't get timed
math.sqrt(n)
# Out:
# 255 ns ± 20.7 ns per loop (mean ± std. dev. of 3 runs, 100 loops each)
-n<N>
: execute the given statement times in a loop. If is not provided, is determined so as to get sufficient accuracy.-r<R>
: number of repeats , each consisting of loops, and take the best result. Default: 7
Both %%time
and %%timeit
can also be used as line magics (with one %
) for timing a single line of code.
Please put %%time
at the very start of the cell even before any comments. This worked for me.
To avoid use of %% again in each cell
Automatic cell execution time
open cmd Run command one by one
- pip install jupyter_contrib_nbextensions
- jupyter contrib nbextension install --user
- jupyter nbextension enable spellchecker/main
- jupyter nbextension enable codefolding/main
It depends on how you want to use the time information...
If you simply want to know how long a cell took to execute for your own knowledge, then the ExecuteTime notebook extension (https://github.com/ipython-contrib/jupyter_contrib_nbextensions/tree/7672d429957aaefe9f2e71b15e3b78ebb9ba96d1/src/jupyter_contrib_nbextensions/nbextensions/execute_time) is a nice solution as it provides time information for all code cells automatically, meaning reduced code maintenance as you don't have to add timing code all over the place. It also writes the last executed date stamp which is useful if you're using the notebook as a scientific log-book.
However, if you want to use the time information programatically, you will need to add code to capture the time information into a variable. As per this answer (Get time of execution of a block of code in Python 2.7), you can use the timeit module:
import timeit
start_time = timeit.default_timer()
# code you want to evaluate
elapsed = timeit.default_timer() - start_time
Obviously, this is not as neat as using cell magic but should get the job done.
As for how / if you can achieve the latter using cell magic, I don't know.