Pyinstrument Profiler

5.1.2 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to profile a section of code using Pyinstrument's `Profiler` class and its `start()`/`stop()` methods, followed by generating both console text output and an interactive HTML report. For profiling an entire script from the command line, you can use `pyinstrument your_script.py`.

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.")

view raw JSON →