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