官术网_书友最值得收藏!

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:

  1. Let's define n:
    In [1]: n = 100000
  2. 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
  3. 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
  4. 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
主站蜘蛛池模板: 南木林县| 磐安县| 锡林浩特市| 亳州市| 甘泉县| 扎赉特旗| 米易县| 绩溪县| 林甸县| 晋城| 南宫市| 文水县| 岢岚县| 马公市| 雅安市| 罗定市| 台州市| 林西县| 营山县| 封丘县| 集贤县| 深水埗区| 锡林郭勒盟| 天峻县| 杭锦后旗| 沙坪坝区| 漾濞| 原阳县| 东辽县| 沁水县| 江西省| 遵义市| 达日县| 白城市| 邵阳市| 拉孜县| 泗洪县| 莒南县| 临洮县| 台南县| 台湾省|