Lesson 1 of 9 · 24m
Profile First: cProfile, pstats, and Sampling Profilers
Optimization without a profile is guessing with extra confidence. Learn what cProfile actually measures, how to read it, and when a sampling profiler is the safer instrument.
Every experienced performance engineer has the same scar: a week spent optimizing code that turned out to be 2% of the runtime. In Python this happens constantly because intuition is misled by syntax. A loop looks hot; the real cost is serialization, a regexp inside a library, or a database round trip nobody remembered adding.
The rule is simple enough to print on a mug: never optimize without a profile of the real workload.
Start with cProfile on a representative path
python -m cProfile -o reports/import-invoices.prof scripts/import_invoices.py --sample data/invoices-10k.csv
python - <<'PY'
import pstats
p = pstats.Stats("reports/import-invoices.prof")
p.strip_dirs().sort_stats("cumulative").print_stats(20)
PYcProfile is deterministic: it instruments function calls and records exact counts. That sounds ideal until you see the overhead — often 1.5x to 3x on call-heavy code. The shape is usually right even when absolute times inflate, but interpret numbers comparatively, not as production truth.
Read the columns like a practitioner
ncalls: how often the function ran. Explosive counts are often the real story.tottime: time inside this function excluding callees. This is where leaf work shows up.cumtime: time including everything it called. Entry points dominate this column.percall: useful for spotting a function that is cheap once but called a million times.
The classic mistake is sorting only by tottime and concluding that len or a codec is "the bottleneck." Those are victims, not causes. Trace upward: who calls them, and why that many times?
When the program is already running, sample it
Sampling profilers interrupt the process periodically and capture stacks. They are lower fidelity about exact call counts but much closer to production cost. py-spy is the standard field tool:
py-spy top --pid 18422
py-spy record --pid 18422 --duration 60 --output reports/api-hot-path.svg
py-spy dump --pid 18422A flamegraph from a busy service often answers the question in one glance: the width of a frame is its share of samples. Deep narrow towers are rarely worth touching; wide plateaus are.
Pick the instrument for the question
Use cProfile when you can reproduce the path locally and want exact call counts. Use py-spy when the cost only appears under production traffic, when native extensions are involved, or when attaching to a live process matters more than perfect accounting.
Field notes
- Profile production-shaped input. A 10-row fixture hides quadratic behavior beautifully.
- One slow endpoint is not one profile; capture the endpoint under realistic concurrency if contention matters.
- Beware profiling only startup or only steady state. Python services often have different hot paths in each.
- Save profiles next to the code change. "It felt faster" has a short shelf life.
Was this lesson helpful?