Book Image

IPython Interactive Computing and Visualization Cookbook

By : Cyrille Rossant
Book Image

IPython Interactive Computing and Visualization Cookbook

By: Cyrille Rossant

Overview of this book

Table of Contents (22 chapters)
IPython Interactive Computing and Visualization Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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...