Install line_profiler
pip install line_profilerTo enable @profile decorator you need to run your code using kernprof script.
According to the documentation:
kernprofwill create an instance ofLineProfilerand 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
@profiledecorator 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.