cProfile is the stdlib’s deterministic profiler. Unlike py-spy, which samples, cProfile instruments every function call — so the overhead is significant (2-5x slowdown on CPU-bound code) and you don’t use it on a production worker handling live traffic. But for a benchmark, a staging replica, or a reproducible test case, cProfile gives you exact call counts and per-function time, which py-spy’s sampling can miss. This article shows the dump-and-convert workflow that ends with a flamegraph you can click through.
How to verify
Check that cProfile and a viewer are available:
python -c "import cProfile, pstats; print('ok')"
pip show snakeviz flameprof 2>/dev/null | grep -E "Name|Version"
which snakeviz flameprof
python -c "import cProfile; cProfile.run('sum(range(1_000_000))', '/tmp/quick.prof')" && ls -lh /tmp/quick.prof
If flameprof is missing, pip install flameprof snakeviz — both are pure Python and have no system deps.
What’s happening
cProfile registers itself as the Python interpreter’s profile callback (sys.setprofile). Every function call, return, and exception goes through the profiler, which records the call site, the callee, and the cumulative + own time. The output is a .prof file containing the call graph with timings, in a binary format that pstats and downstream tools read.
Deterministic profiling has trade-offs that matter operationally. The overhead means you can’t profile under load. The call-graph format is rich enough to show “function foo was called 12,000 times and spent 4.2s total, 0.3s exclusive” — information sampling cannot give you. And because every call is instrumented, you see the exact code path, not a probabilistic reconstruction.
The flamegraph view (Brendan Gregg’s invention) is the same SVG you’d get from py-spy: stacked bars where width is time. Tools to generate it from .prof include flameprof (which writes SVG directly) and snakeviz (which serves an interactive HTML view that’s better for drill-down than for sharing). For a one-shot deliverable in a PR, use flameprof.
The procedure
-
Profile a benchmark or a synthetic load. Wrap the entry point with
cProfile.run:import cProfile, pstats from app.benchmarks import heavy_workload profiler = cProfile.Profile() profiler.enable() heavy_workload(iterations=1000) profiler.disable() profiler.dump_stats("/tmp/bench-$(date +%s).prof") pstats.Stats(profiler).sort_stats("cumulative").print_stats(30) -
For a CLI script you can’t modify, run it under the profiler from the outside:
python -m cProfile -o /tmp/script.prof scripts/import_csv.py inputs/large.csvThe script runs normally; cProfile injects itself and writes the dump on exit.
-
Convert the
.profto a flamegraph SVG. flameprof reads the dump and writes the SVG to stdout:pip install flameprof flameprof /tmp/script.prof > /tmp/script.flame.svgOpen the SVG in a browser. Width is time spent in or under the function; clicking a bar zooms to that call.
-
For interactive analysis, use snakeviz — it starts a local web server with an icicle plot and a sortable stats table:
pip install snakeviz snakeviz /tmp/script.prof --hostname 127.0.0.1 --port 8088Browse to
http://127.0.0.1:8088/. The icicle plot is upside-down compared to flamegraph (entry point at top, leaves at bottom), but the time semantics are the same. -
To get just the top 20 functions by exclusive time without any visualization:
python -c " import pstats s = pstats.Stats('/tmp/script.prof') s.sort_stats('tottime').print_stats(20) "tottimeis exclusive time (time in this function, not including subcalls).cumtimeis cumulative. For optimisation,tottimeis usually what you want — high cumtime but low tottime means the function is just orchestrating, not doing the work. -
For Django, use
django-cprofile-middlewareto profile a single request by URL param:MIDDLEWARE = [ # ... "django_cprofile_middleware.middleware.ProfilerMiddleware", ] DEBUG_TOOLBAR_PANELS = [] # disable to avoid interferenceThen hit any URL with
?profto download the.profdump for that request. Restrict to staff via the middleware’sprof_user_func.
Common pitfalls
- Profiling code that includes I/O — cProfile measures wall time, so a slow database query shows as time in
socket.recv. The optimisation target there is the query, not Python. Cross-reference withEXPLAIN. - Async code under cProfile — every
awaitis a profiler enter/exit event, and the call graph balloons. Useyappiinstead for asyncio code; it understands coroutines. - Profiling a single iteration of a loop and extrapolating — the first iteration includes import time, JIT warm-up, and cache misses. Warm up first, then profile.
- Comparing
.proffiles across Python versions — function names, file paths, and built-in costs shift between minor versions. Compare runs on the same interpreter only. - Forgetting
tottimevscumtime— sorting bycumtimefor “what to optimize” usually points at the entry function, not the slow leaf. Sort bytottimefirst.
For non-deterministic, production-safe profiling that can attach to a live worker, see Profiling Python in production with py-spy. Stack Harbor’s managed operations practice keeps cProfile for benchmarks and one-shot reproductions on staging, and py-spy for everything that runs in production — they answer different questions.