- IPython Interactive Computing and Visualization Cookbook(Second Edition)
- Cyrille Rossant
- 399字
- 2021-07-02 16:23:35
Evaluating the time taken by a command in IPython
The %timeit
magic and the %%timeit
cell magic (which applies to an entire code cell) allow us to quickly evaluate the time taken by one or several Python statements. The next recipes in this chapter will show methods for more extensive profiling.
How to do it...
We are going to estimate the time taken to calculate the sum of the inverse squares of all positive integer numbers up to a given n
.
- Let's define
n
:>>> n = 100000
- Let's time this computation in pure Python:
>>> %timeit sum([1. / i**2 for i in range(1, n)]) 21.6 ms ± 343 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)
- Now, let's use the
%%timeit
cell magic to time the same computation written on two lines:>>> %%timeit s = 0. for i in range(1, n): s += 1. / i**2 22 ms ± 522 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)
- Finally, let's time the NumPy version of this computation:
>>> import numpy as np >>> %timeit np.sum(1. / np.arange(1., n) ** 2) 160 μs ± 959 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Here, the NumPy vectorized version is 137x faster than the pure Python version.
How it works...
The %timeit
command accepts several optional parameters. One such parameter is the number of statement evaluations. By default, this number is chosen automatically so that the %timeit
command returns within a few seconds in most cases. However, this number can be specified directly with the -r
and -n
parameters. Type %timeit?
in IPython to get more information.
The %%timeit
cell magic also accepts an optional setup statement in the first line (on the same line as %%timeit
), which is executed but not timed. All variables created in this statement are available inside the cell.
There's more...
If you are not in an IPython interactive session or in a Jupyter Notebook, you can use import timeit; timeit.timeit()
. This function benchmarks a Python statement stored in a string. IPython's %timeit
magic command is a convenient wrapper around timeit()
, useful in an interactive session. For more information on the timeit
module, refer to https://docs.python.org/3/library/timeit.html.
See also
- The Profiling your code easily with cProfile and IPython recipe
- The Profiling your code line-by-line with line_profiler recipe
- 計算機綜合設計實驗指導
- 文本數據挖掘:基于R語言
- Neural Network Programming with TensorFlow
- 區塊鏈通俗讀本
- UDK iOS Game Development Beginner's Guide
- 深入淺出MySQL:數據庫開發、優化與管理維護(第2版)
- 大數據時代下的智能轉型進程精選(套裝共10冊)
- 數據庫原理與設計(第2版)
- SQL優化最佳實踐:構建高效率Oracle數據庫的方法與技巧
- Splunk智能運維實戰
- 二進制分析實戰
- Gideros Mobile Game Development
- Mastering ROS for Robotics Programming(Second Edition)
- openGauss數據庫核心技術
- 數據庫原理與設計實驗教程(MySQL版)