Install line_profiler
pip install line_profiler
To enable @profile
decorator you need to run your code using kernprof
script.
According to the documentation:
kernprof
will create an instance ofLineProfiler
and insert it into the__builtins__
namespace with the name profile
However, when running Django / Flask applications, you will want to run the whole code using the corresponding commands. To be able to profile your code in that case, you can use the following trick:
- Add these lines on top of the module:
import line_profiler
profile = line_profiler.LineProfiler()
-
Add
@profile
decorator to the function / method you want to profile. -
Add
profile.print_stats()
before the return statement to print the profile. You can set the output unit usingprofile.print_stats(output_unit=1e-3)
And that's all.