如何使用 %%timeit cell magic 并排除设置代码?

wim*_*wim 3 python profiling timing ipython ipython-magic

%timeit魔术支持行模式和小区模式执行。使用单元格模式,调用%%timeit(注意:两个百分比符号),可用于从测量中排除一些设置代码:

%%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code code code...
Run Code Online (Sandbox Code Playgroud)

但是你如何使用它呢?这给出了一个错误:

>>> %%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 %)?
Run Code Online (Sandbox Code Playgroud)

这并不排除基准测试中的第一行:

>>> %%timeit
... sleep(0.1)
... sleep(0.1)
... 
200 ms ± 17.6 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
Run Code Online (Sandbox Code Playgroud)

wim*_*wim 5

将设置放在第一行,将正文放在下一行:

>>> %%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)
Run Code Online (Sandbox Code Playgroud)