O'Reilly logo

NumPy Cookbook - Second Edition by Ivan Idris

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required