Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use %%timeit cell magic and exclude setup code?

The %timeit magic supports execution in line mode and cell mode. Using the cell mode, invoked with %%timeit (note: two percent symbols), can be used to exclude some setup code from the measurement:

%%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code code code...

But how do you use it? This gives an error:

>>> %%timeit sleep(0.1); sleep(0.1)
... 
UsageError: %%timeit is a cell magic, but the cell body is empty. 
Did you mean the line magic %timeit (single %)?

And this doesn't exclude the first line from the benchmark:

>>> %%timeit
... sleep(0.1)
... sleep(0.1)
... 
200 ms ± 17.6 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
like image 980
wim Avatar asked Mar 08 '23 01:03

wim


1 Answers

Put the setup on the first line, and the body on the next line(s):

>>> %%timeit sleep(0.1)
... sleep(0.2)
... sleep(0.3)
... 
500 ms ± 14.1 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
like image 110
wim Avatar answered Mar 16 '23 01:03

wim