Profiling code with line_profiler

Now that we installed line_profiler, we can start profiling.

How to do it...

Obviously, we will need some code to profile.

  1. Write code to profile.

    We will write code to multiply a random matrix of varying size with itself. Also, the thread will sleep for a few seconds. The function to profile will be annotated with @profile:

    import numpy
    import time
    
    @profile
    def multiply(n):
      A = numpy.random.rand(n, n)
      time.sleep(numpy.random.randint(0, 2))
      return numpy.matrix(A) ** 2
    
    for n in 2 ** numpy.arange(0, 10):
      multiply(n)
  2. Profile the code.

    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        13461   1346.1      0.4     A = numpy.random.rand(n, n)
         7        10      3000689 300068.9     93.9     time.sleep(numpy.random.randint(0, 2))
         8        10       182386  18238.6      5.7     return numpy.matrix(A) ** 2
    

How it works...

The @profile decorator tells line_profiler which functions to profile. The following table explains the output of the profiler:

Column

Description

Line #

The line number in the file.

Hits

The number of times the line was executed.

Time

Time spent executing the line.

Per Hit

Average time spent executing the line.

% Time

Percentage of time spent executing the line relative to the time spent executing all the lines.

Line Contents

The contents of the line.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset