- IPython Interactive Computing and Visualization Cookbook
- Cyrille Rossant
- 363字
- 2021-08-05 17:57:28
Evaluating the time taken by a statement in IPython
The %timeit
magic and the %%timeit
cell magic (that applies to an entire code cell) allow you to quickly evaluate the time taken by one or several Python statements. For more extensive profiling, you may need to use more advanced methods presented in the next recipes.
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
:In [1]: n = 100000
- Let's time this computation in pure Python:
In [2]: %timeit sum([1. / i**2 for i in range(1, n)]) 10 loops, best of 3: 131 ms per loop
- Now, let's use the
%%timeit
cell magic to time the same computation written on two lines:In [3]: %%timeit s = 0. for i in range(1, n): s += 1. / i**2 10 loops, best of 3: 137 ms per loop
- Finally, let's time the NumPy version of this computation:
In [4]: import numpy as np In [5]: %timeit np.sum(1. / np.arange(1., n) ** 2) 1000 loops, best of 3: 1.71 ms per loop
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. 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, you can use timeit.timeit()
. This function, defined in Python's timeit
module, 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
- HTML5+CSS3王者歸來
- Mastering OpenLayers 3
- MySQL數(shù)據(jù)庫應用與管理 第2版
- INSTANT MinGW Starter
- Ray分布式機器學習:利用Ray進行大模型的數(shù)據(jù)處理、訓練、推理和部署
- Building Mapping Applications with QGIS
- 小程序開發(fā)原理與實戰(zhàn)
- 零基礎(chǔ)學單片機C語言程序設(shè)計
- 大模型RAG實戰(zhàn):RAG原理、應用與系統(tǒng)構(gòu)建
- Illustrator CC平面設(shè)計實戰(zhàn)從入門到精通(視頻自學全彩版)
- Visual Basic程序設(shè)計(第三版)
- Visual Basic 程序設(shè)計實踐教程
- Java高手是怎樣煉成的:原理、方法與實踐
- Hands-On Artificial Intelligence with Unreal Engine
- C#編程魔法書