Skip to content

Profiling and performance

Phase 4 · Concurrency and performance · 15 min read

What you'll be able to do

  • Set a performance target, run a repeatable measurement, and decide whether a change helped.
  • Read a Python function profile to find repeated work and distinguish self time from cumulative time.
  • Choose useful CPU, memory, or I/O fixes and stop when the requirement is met.

Start with a requirement and a baseline

Measure, don't guess. “Make it faster” gives no way to tell when you are done. Pick a workload and a target: for example, “process 10,000 records in under 2 seconds,” “serve 100 requests per second while keeping the 95th-percentile latency (the time within which 95% of requests finish) under 300 ms,” or “keep peak memory below 1 GB.” Latency is time per request; throughput is completed work per unit time; memory can limit how many jobs fit on one machine. Improving one may worsen another.

Run representative input several times and record the spread and a typical value. Include data size, cache state, and worker count. Change one thing, rerun, and check correctness. If the result moves less than the run-to-run noise, you have not shown an improvement. A tiny sample can hide poor scaling; see data structures and Big-O.

The performance loop: measure, profile, change one thing, measure again, then find the next bottleneck.

Small measurements can answer small questions

The shell's time measures an entire command, including startup. Python's timeit repeats a small statement and is useful when comparing two local operations. time.perf_counter() measures elapsed wall time around a larger block:

import time

start = time.perf_counter()
result = process(records)
elapsed = time.perf_counter() - start
print(f"{elapsed:.3f} seconds for {len(records)} records")

For a membership comparison, try python -m timeit -s 'items=list(range(1000))' '999 in items', then use items=set(range(1000)) as setup. Setup is outside the timed statement; if each request builds a set, measure that cost too. Warm-up can populate caches, so separate warm and cold cases when both matter. Repeat measurements to account for noise. A microbenchmark cannot show whether an operation matters to the whole pipeline.

Also distinguish wall time from CPU time. Waiting for a network response increases wall time while using little CPU. perf_counter() gives elapsed wall time; time.process_time() measures CPU consumed by the current process. It does not include worker subprocesses, so for total CPU use across processes, add up each process's CPU time or use a system-level metric. More CPU workers can shorten wall time while increasing total CPU use. Measure the quantity your target names.

Profile the real path

cProfile records function calls and timing; pstats sorts and displays them. In the lab directory, this command profiles a supplied workload. The excerpt below is from one run, so your numbers will differ:

PYTHONPATH=starter python - <<'PY'
import cProfile
import pstats
from lab import _profile_workload

profile = cProfile.Profile()
profile.runcall(_profile_workload)
pstats.Stats(profile).strip_dirs().sort_stats("cumtime").print_stats(3)
PY
         240799 function calls (240795 primitive calls) in 0.044 seconds

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.044    0.044 lab.py:44(_profile_workload)
        1    0.000    0.000    0.044    0.044 lab.py:28(_slow_pipeline)
       80    0.027    0.000    0.044    0.001 lab.py:16(expensive)

ncalls is the number of calls. Total time (tottime) is time inside the function itself; cumulative time includes its callees. Here _slow_pipeline has almost no self time but owns nearly all the cumulative time. expensive runs 80 times; the gap between its 0.027 s total time and 0.044 s cumulative time is spent in its callees, here the built-in sum. Removing repeated calls is more promising than tuning the outer loop. Sort by cumtime to find slow paths, then by tottime to find where time is spent. A profiler adds overhead, so compare before and after with a separate benchmark. Blocking I/O can also appear in elapsed profiles; use CPU and wall measurements together to avoid treating a wait as computation.

A sampling profiler periodically observes the stack instead of recording every call. Tools such as py-spy can show a flame graph: width represents how often a stack appears in samples; vertical layers show callers. Sampling suits long-running processes but can miss short functions. Line-level profilers can locate an expensive line after a function profile narrows the search.

Change the work, not just the syntax

Start with the biggest source of work. Replace a poor algorithm or data structure; avoid repeating the same calculation; then batch I/O or calls. For example, if 10,000 records check membership in a 1,000-element list, the worst case is roughly 10 million comparisons. Building a set once and doing 10,000 lookups changes the growth pattern. Hoist constant regex setup out of a loop, even if the runtime caches compiled patterns, and memoize a pure calculation when inputs repeat. Give caches a capacity limit and a rule for invalidation when source data changes; caching and CDNs covers those trade-offs. One common capacity rule is LRU (least recently used): when the cache is full, drop the entry that has gone unused longest. With capacity two, accesses A, B, A, C evict B, because the second access to A is a hit that makes A the most recent. A caching decorator keeps its entries and hit/miss counts between calls, so later calls can reuse them.

Next, move suitable bulk work into native code (vectorization), use the right container, and avoid needless copies or serialization. Consider concurrency or lower-level code only when the profile supports it: concurrency overlaps independent waits but does not speed up every CPU-bound Python loop.

Amdahl's law limits the payoff from speeding up one part. If a stage takes 20% of runtime and becomes 10 times faster, the new total is 0.80 + 0.20/10 = 0.82 of the old total. Overall speedup is 1/0.82 = 1.2195, about 1.22 times, not 10 times. Once that stage shrinks, profile again: a different stage may dominate.

Memory needs its own measurement

Track peak memory as well as steady-state memory. A program may usually sit at 200 MB yet briefly need another 2 GB while loading and converting a file. tracemalloc can compare Python allocation snapshots and report a measured peak:

import tracemalloc

tracemalloc.start()
result = process(records)
current, peak = tracemalloc.get_traced_memory()
print(current, peak)  # bytes tracked since start

The tracked peak covers allocations tracemalloc observes, not necessarily full resident memory; native libraries may hold large buffers. A Python “leak” often means references remain reachable: a global list or unbounded cache keeps objects alive. Stream records with a generator when you need one at a time; list(generator) materializes them all. Avoid copying large objects during conversion or serialization. With copy-on-write after a process fork, workers may initially share pages, but mutation can make private copies. Measure memory after real work, not just startup.

I/O, regression guards, and stopping

For files and sockets, many tiny reads or writes pay overhead repeatedly. Buffer data and choose a chunk size that reduces calls without creating an excessive peak allocation. Text JSON is easy to inspect and interoperable; a suitable binary format may reduce parse work or size, but adds a format contract. Compression can reduce transferred bytes while adding CPU time, so test the combination on the real path. Across a network, round trips often matter more than local parsing: batching 100 independent small calls into 10 batches cuts 90 round trips, subject to API limits and changed failure behavior. See latency and throughput for how queues affect the result.

Stop when the measured target is met with margin and the code remains understandable. A clever micro-optimization in a cold function is usually a poor trade. Keep a regression guard: a benchmark in CI can use a generous threshold because shared machines vary, while a test that counts expensive calls, copies, or network requests is often more stable. Recheck the result on representative data when the workload changes.

For AI engineers

For AI engineers

A training script that “waits on the GPU” may actually spend its wall time loading examples, decoding data, or tokenizing each row in a Python loop. Time data loading, preprocessing, model execution, and postprocessing separately before changing the model. A per-row function over millions of rows can be the bottleneck even when each call looks cheap.

In inference, constructing a model or client inside a request loop repeats setup; batch compatible requests when latency and limits allow it. Caching embeddings for repeated inputs can save computation, but the key must include every input that changes the result and the cache needs bounds. Use the same measurement loop for the whole pipeline, not a tiny synthetic model call.

Common mistakes

  • Optimizing from intuition before profiling the representative path.
  • Running one benchmark once and treating a small difference as proof.
  • Profiling debug mode or tiny data when production runs at a different scale.
  • Tuning a cold function because it looks slow in isolation.
  • Caching results without a size bound or a way to handle changed inputs.
  • Calling a wall-time wait “CPU work” and adding workers without checking where time went.

Check yourself

A function uses 50% of total time, and you make it twice as fast. What is the maximum overall speedup?

The new runtime is 0.50 + 0.50/2 = 0.75 of the old one, so overall speedup is 1/0.75, about 1.33 times.

Your profile shows a wrapper with high cumulative time and near-zero total time. Where should you look next?

Inspect its callees. The wrapper owns a slow path but spends little time in its own body; sorting by total time helps locate work inside that path.

A batch job's wall time falls when you use four workers, but total CPU time rises. Is that necessarily a bad result?

No. Parallel work can finish earlier while consuming more aggregate CPU. Judge it against the latency, throughput, cost, and memory targets you set before changing it.

An embedding cache grows every day and process memory never falls. What should you inspect?

Check whether cached entries remain referenced, set a capacity limit, and verify the key and invalidation rule. Compare steady-state and peak memory under representative input.

Lab

Work in code/profiling-performance/ on a correct but wasteful text pipeline. Use a supplied cProfile helper to identify the hotspot. Move the repeated re.compile call out of the record loop; remove linear membership checks and repeated scoring. Add a wall-clock Timer and a bounded LRU cache with hit/miss counts. The tests check results and count operations instead of timing them. Run: cd code/profiling-performance && PYTHONPATH=starter python -m pytest tests -q

Go deeper