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.

  1. Let's define n:
    >>> n = 100000
  2. 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)
  3. 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, ...

Get IPython Interactive Computing and Visualization Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.