Book Image

IPython Interactive Computing and Visualization Cookbook - Second Edition

By : Cyrille Rossant
Book Image

IPython Interactive Computing and Visualization Cookbook - Second Edition

By: Cyrille Rossant

Overview of this book

Python is one of the leading open source platforms for data science and numerical computing. IPython and the associated Jupyter Notebook offer efficient interfaces to Python for data analysis and interactive visualization, and they constitute an ideal gateway to the platform. IPython Interactive Computing and Visualization Cookbook, Second Edition contains many ready-to-use, focused recipes for high-performance scientific computing and data analysis, from the latest IPython/Jupyter features to the most advanced tricks, to help you write better and faster code. You will apply these state-of-the-art methods to various real-world examples, illustrating topics in applied mathematics, scientific modeling, and machine learning. The first part of the book covers programming techniques: code quality and reproducibility, code optimization, high-performance computing through just-in-time compilation, parallel computing, and graphics card programming. The second part tackles data science, statistics, machine learning, signal and image processing, dynamical systems, and pure and applied mathematics.
Table of Contents (19 chapters)
IPython Interactive Computing and Visualization CookbookSecond Edition
Contributors
Preface
Index

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, n):
            s += 1. / i**2
    22 ms ± 522 µs per loop (mean ± std. dev. of 7 runs,
        10 loops each)
  4. Finally, let's time the NumPy version of this computation:

    >>> import numpy as np
    >>> %timeit...