Pyinstrument Profiler
Pyinstrument is a powerful call stack profiler for Python that helps developers understand why their code is slow. It operates by sampling the call stack at regular intervals, providing a clear, interactive visualization of time spent in different functions. The current stable version is 5.1.2, and the library maintains an active release cadence with frequent updates addressing bugs and introducing new features, particularly around its HTML rendering capabilities.
Warnings
- breaking In Pyinstrument v5.0.0, the mechanism for detecting 'library' code (code not directly part of your application) was changed. This might alter how the profiler categorizes and displays frames, potentially affecting filtering or interpretation of results for users who relied on the previous classification.
- gotcha Pyinstrument, like most profilers, introduces some overhead. While it's designed to be low-overhead, profiling very short-lived functions or extremely high-frequency code paths can still show distorted results. The sampling interval (`--interval` CLI option or `Profiler(interval=...)` parameter) can affect both overhead and precision.
- gotcha Mismatched calls to `profiler.start()` and `profiler.stop()` can lead to 'call stack without an active session' errors or incomplete profiles. This often happens in complex control flows or when exceptions interrupt profiling.
- breaking Pyinstrument versions prior to 4.7.3 could crash on Python 3.12 and later when profiling code that mutates the `locals()` dictionary, affecting compatibility with certain libraries (e.g., `glom`).
Install
-
pip install pyinstrument
Imports
- Profiler
from pyinstrument import Profiler
- HTMLRenderer
from pyinstrument.renderers import HTMLRenderer
- ConsoleRenderer
from pyinstrument.renderers import ConsoleRenderer
Quickstart
from pyinstrument import Profiler
import time
import os
def my_slow_function():
time.sleep(0.05)
another_slow_part()
def another_slow_part():
time.sleep(0.02)
# Using the context manager (recommended for specific code blocks)
profiler = Profiler()
profiler.start()
for _ in range(5):
my_slow_function()
profiler.stop()
# Output to console
print("\n--- Console Output ---")
print(profiler.output_text(unicode=True, color=True))
# Generate HTML report
# For simplicity, we'll write to a file directly. In a real app,
# you might return this HTML via a web framework.
html_output = profiler.output_html()
output_filename = os.path.join(os.getcwd(), "pyinstrument_profile.html")
with open(output_filename, "w") as f:
f.write(html_output)
print(f"\nHTML report saved to: {output_filename}")
print("Open the HTML file in your browser to view the interactive profile.")