Now that we installed line_profiler
, we can start profiling.
Obviously, we will need some 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)
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
The
@profile
decorator tells line_profiler
which functions to profile. The following table explains the output of the profiler:
Column |
Description |
---|---|
The line number in the file. | |
The number of times the line was executed. | |
Time spent executing the line. | |
Average time spent executing the line. | |
Percentage of time spent executing the line relative to the time spent executing all the lines. | |
The contents of the line. |