pyinstrumen
pyinstrument
Profile a Python script
Call Pyinstrument directly from the command line. Instead of writing python script.py
, type pyinstrument script.py
. Your script will run as normal, and at the end (or when you press ^C
), Pyinstrument will output a colored summary showing where most of the time was spent.
Here are the options you can use:
|
|
Protip: -r html
will give you a interactive profile report as HTML - you can really explore this way!
Profile a specific chunk of code
Pyinstrument also has a Python API. Just surround your code with Pyinstrument, like this:
|
|
If you get “No samples were recorded.” because your code executed in under 1ms, hooray! If you still want to instrument the code, set an interval value smaller than the default 0.001 (1 millisecond) like this:
|
|
Experiment with the interval value to see different depths, but keep in mind that smaller intervals could affect the performance overhead of profiling.
Protip: To explore the profile in a web browser, use profiler.open_in_browser()
. To save this HTML for later, use profiler.output_html()
.
Profile a web request in Django
To profile Django web requests, add pyinstrument.middleware.ProfilerMiddleware
to MIDDLEWARE_CLASSES
in your settings.py
.
Once installed, add ?profile
to the end of a request URL to activate the profiler. Your request will run as normal, but instead of getting the response, you’ll get pyinstrument’s analysis of the request in a web page.
If you’re writing an API, it’s not easy to change the URL when you want to profile something. In this case, add PYINSTRUMENT_PROFILE_DIR = 'profiles'
to your settings.py
. Pyinstrument will profile every request and save the HTML output to the folder profiles
in your working directory.
If you want to show the profiling page depending on the request you can define PYINSTRUMENT_SHOW_CALLBACK
as dotted path to a function used for determining whether the page should show or not. You can provide your own function callback(request) which returns True or False in your settings.py.
|
|
Profile a web request in Flask
A simple setup to profile a Flask application is the following:
|
|
This will check for the ?profile
query param on each request and if found, it starts profiling. After each request where the profiler was running it creates the html output and returns that instead of the actual response.