On this page
  1. cProfile
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Profiling a Script from the Command Line & Saving .prof Output
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects

cProfile

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


Import

import cProfile

Overview

Deterministic C-extension CPU profiler (Profile, run, python -m cProfile) that records exact call counts, self time (tottime), and cumulative time (cumtime) for every Python function with low overhead. Always prefer cProfile over the pure-Python profile module, and inspect saved profiles with pstats.

Quick Start

import cProfile
import pstats

with cProfile.Profile() as pr:
    _ = sum(i * i for i in range(50_000))

stats = pstats.Stats(pr).sort_stats("cumtime")
assert stats.total_calls > 0

Implementation Walkthrough

1. Profiling a Script from the Command Line & Saving .prof Output

# Print top 20 functions by cumulative time:
python3 -m cProfile -s cumtime my_script.py | head -n 30

# Save binary profile for interactive inspection with pstats or snakeviz:
python3 -m cProfile -o run.prof my_script.py

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes