On this page
  1. pstats
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Filtering & Inspecting Callers / Callees
  7. Gotchas & Boundaries
  8. Classes & Objects

pstats

Prev: profile | Up: stdlib_module | Next: pty
Rel: typing, annotationlib, pydoc, pydoc_data, doctest
Ref: docs.python.org — pstats
Tags: #public #python3 #stdlib


Import

import pstats

Overview

Loads, filters, merges, and sorts binary profile dumps produced by cProfile (Stats, SortKey, strip_dirs, print_stats, print_callers, print_callees). Essential for turning raw .prof files into actionable bottleneck reports.

Quick Start

import cProfile
import io
import pstats

with cProfile.Profile() as pr:
    _ = sorted(range(10_000, 0, -1))

out = io.StringIO()
pstats.Stats(pr, stream=out).strip_dirs().sort_stats(pstats.SortKey.CUMULATIVE).print_stats(5)
assert "function calls" in out.getvalue()

Implementation Walkthrough

1. Filtering & Inspecting Callers / Callees

import pstats

def top_report(prof_path: str, limit: int = 15) -> None:
    stats = pstats.Stats(prof_path)
    stats.strip_dirs()
    stats.sort_stats(pstats.SortKey.TIME)
    stats.print_stats(limit)
    stats.print_callers(5)

Gotchas & Boundaries

Classes & Objects

Linked from

Related notes