Profiling

A track of P34 · Performance & Profiling.

Measure before you optimise: read a cProfile to find the hot function, and profile allocations with tracemalloc - so you fix the code that is actually slow, not the code you guessed was slow.

Every performance story starts the same way: someone is sure they know why the code is slow, and they are wrong. This track replaces the guess with a measurement. Python ships two profilers that answer the two questions that matter — where does the time go? and where does the memory go? — and learning to read them is the difference between fixing the bottleneck and polishing a part that was never the problem.

cProfile answers the time question: it records how many times each function ran and how long it took, so the hot spot is the function the profile points at, not the one you suspected. The single most useful column is often the call count — it is deterministic, so a tiny function called a million times stands out regardless of how fast the machine is. tracemalloc answers the memory question: it traces allocations, reports the peak, and — through snapshot diffs — attributes growth to the exact line that keeps allocating. Together they turn "it feels slow" into a number and a location.

The track's motto is the pillar's motto: always profile before you optimise. It closes by pointing forward — the optimisation track acts on what the profile finds, and P3 (Computing Fundamentals) explains why the hardware makes a given line slow in the first place.

Reproduce the slow casea realistic inputProfile timecProfile — which functionProfile memorytracemalloc — peak & leaksHand off to optimisationact on the evidence
Measure first: find where before you decide how to fix it.