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 code with line_profiler


Now that we've installed line_profiler, we can start profiling.

How to do it...

Obviously, we will need code to profile:

  1. Write the following code to multiply a random matrix of varying size by itself. Also, the thread will sleep for a few seconds. Annotate the function to profile with @profile:

    import numpy as np
    import time
    
    @profile
    def multiply(n):
      A = np.random.rand(n, n)
      time.sleep(np.random.randint(0, 2))
      return np.matrix(A) ** 2
    
    for n in 2 ** np.arange(0, 10):
      multiply(n)
  2. Run the profiler with the following command:

    $ kernprof.py -l -v mat_mult.py 
    Wrote profile results to mat_mult.py.lprof
    Timer unit: 1e-06 s
    
    File: mat_mult.py
    Function: multiply at line 4
    Total time: 3.19654 s
    
    Line #      Hits         Time  Per Hit   % Time  Line Contents
    ==============================================================
         4                                           @profile
         5                                           def multiply(n):
         6        10  ...