Skip to content

Instantly share code, notes, and snippets.

@fferrin
Last active February 25, 2020 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fferrin/e6d2f8bcd10ee00219f69b418dd13789 to your computer and use it in GitHub Desktop.
Save fferrin/e6d2f8bcd10ee00219f69b418dd13789 to your computer and use it in GitHub Desktop.
Profile Django / Flask endpoints.

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 of LineProfiler 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:

  1. Add these lines on top of the module:
import line_profiler
profile = line_profiler.LineProfiler()
  1. Add @profile decorator to the function / method you want to profile.

  2. Add profile.print_stats() before the return statement to print the profile. You can set the output unit using profile.print_stats(output_unit=1e-3)

And that's all.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment