Book Image

NumPy Cookbook - Second Edition

By : Ivan Idris
Book Image

NumPy Cookbook - Second Edition

By: Ivan Idris

Overview of this book

<p>NumPy has the ability to give you speed and high productivity. High performance calculations can be done easily with clean and efficient code, and it allows you to execute complex algebraic and mathematical computations in no time.</p> <p>This book will give you a solid foundation in NumPy arrays and universal functions. Starting with the installation and configuration of IPython, you'll learn about advanced indexing and array concepts along with commonly used yet effective functions. You will then cover practical concepts such as image processing, special arrays, and universal functions. You will also learn about plotting with Matplotlib and the related SciPy project with the help of examples. At the end of the book, you will study how to explore atmospheric pressure and its related techniques. By the time you finish this book, you'll be able to write clean and fast code with NumPy.</p>
Table of Contents (19 chapters)
NumPy Cookbook Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Profiling with IPython


In IPython, we can profile small snippets of code using timeit. We can also profile a larger script. We will show both approaches.

How to do it...

First, we will time a small snippet:

  1. Start IPython in pylab mode:

    $ ipython --pylab

    Create an array containing 1000 integer values between 0 and 1000:

    In [1]: a = arange(1000)

    Measure the time taken for searching "the answer to everything"—42, in the array. Yes, the answer to everything is 42. If you don't believe me, read http://en.wikipedia.org/wiki/42_%28number%29:

    In [2]: %timeit searchsorted(a, 42)
    100000 loops, best of 3: 7.58 us per loop
  2. Profile the following small script that inverts a matrix of varying size containing random values. The .I attribute (that's an uppercase I) of a NumPy matrix represents the inverse of that matrix:

    import numpy as np
    
    def invert(n):
      a = np.matrix(np.random.rand(n, n))
    
      return a.I
    
    sizes = 2 ** np.arange(0, 12)
    
    for n in sizes:
      invert(n)

    Time this code as follows:

    In [1]: %run -t invert_matrix...