Objective
Programmers are reliably bad at guessing where time goes. By the end of this lesson you should be able to profile a slow program, read the profile correctly, find the one change that matters, and quantify the improvement. Timings below are from one laptop; the ratios, not the absolute numbers, are the point.
The tools
| Question | Tool |
|---|---|
| Which functions take the time? | cProfile + pstats (standard library, deterministic: records every call) |
| Which lines inside a function? | line_profiler (decorate with @profile, run kernprof -l -v script.py) |
| What is a live or long-running process doing? | a sampling profiler such as py-spy (attaches to a running PID, low overhead) |
| How long does this small snippet take? | timeit |
| Where is memory allocated? | tracemalloc (standard library) |
Run cProfile on a whole script with python -m cProfile -s tottime script.py, or from code:
import cProfile
import pstats
cProfile.run("run(prices, blackout)", "out.prof")
pstats.Stats("out.prof").sort_stats("tottime").print_stats(6)
The two time columns mean different things. tottime is time spent in the function's own code, excluding functions it calls. cumtime includes everything it calls. Sort by cumtime to see which high-level step is slow; sort by tottime to find where the work actually happens. ncalls tells you whether a function is slow per call or merely called a million times.
Worked example
find the real bottleneck
This toy backtest takes about 0.3 s for 20,000 days. It counts days whose return exceeds twice the trailing 20-day volatility, skipping blackout days. Most people would guess the volatility calculation is the problem. Profile it.
import math
import random
def make_data(n: int, seed: int = 0) -> tuple[list[float], list[int]]:
rng = random.Random(seed)
prices = [100.0]
for _ in range(n - 1):
prices.append(prices[-1] * math.exp(rng.gauss(0.0, 0.01)))
blackout = rng.sample(range(n), n // 10) # days we may not trade
return prices, blackout
def rolling_vol(rets: list[float], i: int, window: int) -> float:
w = rets[i - window:i]
m = sum(w) / window
return math.sqrt(sum((x - m) ** 2 for x in w) / (window - 1))
def run(prices: list[float], blackout: list[int], window: int = 20) -> int:
rets = [math.log(b / a) for a, b in zip(prices, prices[1:])]
trades = 0
for i in range(window, len(rets)):
if i in blackout:
continue
if abs(rets[i]) > 2 * rolling_vol(rets, i, window):
trades += 1
return trades
Show solutionHide solution
487485 function calls in 0.420 seconds
Ordered by: internal time
List reduced from 12 to 6 due to restriction <6>
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.292 0.292 0.420 0.420 backtest.py:20(run)
377580 0.070 0.000 0.070 0.000 backtest.py:17(<genexpr>)
35960 0.030 0.000 0.101 0.000 {built-in method builtins.sum}
17980 0.019 0.000 0.121 0.000 backtest.py:14(rolling_vol)
1 0.004 0.004 0.005 0.005 backtest.py:21(<listcomp>)
17980 0.002 0.000 0.002 0.000 {built-in method builtins.abs}
(Paths shortened.) Read it carefully:
rolling_volhas cumtime 0.121 s of 0.420 s: under 30%. The guess was wrong.runitself has tottime 0.292 s, about 70% of the total, spent in its own lines rather than in any function it calls. The only expensive line inrun's own code isi in blackout: membership in a 2,000-element list is a linear scan, executed about 20,000 times. Operators likeinon built-in types do not appear as separate rows, which is the limitation of a function-level profiler;line_profilerwould attribute the time to that line directly.- The call counts check out: there are 19,979 loop iterations, and the 17,980 that are not blackout days call
rolling_volonce each, which callssumtwice (35,960) and runs a generator yielding 20 values plus one final resume (17,980 × 21 = 377,580).
The fix is one line: banned = set(blackout) before the loop and if i in banned. Timed with timeit (best of 5 repeats), the program goes from about 300 ms to about 39 ms, a 7.5× speed-up, with identical output (1,110 signals).
Profile again and the picture changes: now the generator inside rolling_vol is the top tottime row. Optimisation is iterative: fix the top item, re-profile, stop when the program is fast enough. The next step is algorithmic or vectorised. A NumPy version computes all rolling standard deviations at once with sliding_window_view(rets[:-1], 20).std(axis=1, ddof=1) and a boolean mask for blackout days, again giving 1,110, in about 3.1 ms: another 12× and about 95× overall.
Profiler overhead and timeit
cProfile adds a fixed cost to every function call, so it distorts call-heavy code. Under the profiler the set-based version reported 0.116 s; timed normally it takes 39 ms. The 377,580 generator resumptions are each charged overhead. Use the profile to find where time goes, and timeit to measure how much a change saves.
$ python -m timeit -s "import random; xs=[random.random() for _ in range(1_000_000)]" "sum(x*x for x in xs)"
5 loops, best of 5: 36 msec per loop
$ python -m timeit -s "import numpy as np; a=np.random.default_rng(0).random(1_000_000)" "(a*a).sum()"
100 loops, best of 5: 1.78 msec per loop
$ python -m timeit -s "import numpy as np; a=np.random.default_rng(0).random(1_000_000)" "a @ a"
1000 loops, best of 5: 196 usec per loop
Rules for honest timing:
- Put setup in
-s(orsetup=) so it is not timed. - Report the minimum of several repeats (
timeit.repeat). Noise from other processes only ever adds time, so the minimum is the best estimate of the code's cost; the mean mixes in the noise. - Time realistic sizes. A vectorised version can lose on 10 elements, where fixed call overhead dominates, and win by 100× on a million.
- Check that both versions return the same answer before comparing their speed.
The three lines above show typical ratios: a Python generator over a million floats about 36 ms, NumPy's elementwise multiply and sum about 20× faster, and a single BLAS dot product (a @ a, one pass, no temporary array) another 9× faster. Vectorising usually buys 10–100× over interpreted loops for simple arithmetic. It buys little when the work is already in C (a single large sort or matrix multiply), and nothing when the loop body is a call into a slow external service.
Amdahl's law: how much can this help?
If a fraction of the run time is in the part you speed up by a factor , the overall speed-up is
As , . Making a function that takes 30% of the time ten times faster gives ; making it infinitely fast gives at most . In the backtest, the list membership was about 70% of the profiled time, which is why one line made such a difference. Profile first so you spend effort where is large.
Knowledge check
In a cProfile report, function f has tottime 0.02 s and cumtime 3.5 s out of a 4 s run. What does that mean?
Knowledge check
A function takes 30% of a pipeline's run time. You make it 10 times faster. What is the overall speed-up?
Knowledge check
Why should timeit results be summarised by the minimum of several repeats rather than the mean?
Key takeaways
- Never optimise from a guess: profile with cProfile, then confirm the gain with
timeit(minimum of repeats, realistic sizes, same output). - tottime is the function's own work, cumtime includes callees; operators such as
inshow up in the caller's tottime, which is when line-level profiling helps. - The common culprits are wrong data structures, repeated work, and Python loops over large numeric arrays.
- Profiler overhead inflates call-heavy code; profile to locate, time to measure.
- Amdahl: overall speed-up is capped at ; vectorising simple arithmetic usually buys 10–100×.
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).