Sub topic 1
Why you measure before you optimize
Prerequisites
This chapter assumes you can write and run Python functions, loops, and modules from a terminal. You should know how to use lists, dicts, and sets, and how to install packages with pip. No profiling experience is needed.
The problem with guessing
Programmers are poor at predicting where a program spends its time. A loop that looks expensive may run in microseconds, while a harmless-looking line may dominate the run. Optimizing without data often produces code that is harder to read and no faster.
Donald Knuth's warning is often quoted as "premature optimization is the root of all evil." The point is not that speed is unimportant. It is that effort spent on code that is not the bottleneck (the part that limits overall speed) is wasted.
Amdahl's law gives the arithmetic. If a function takes 5% of the total run time, making it ten times faster saves only 4.5% of the total. If another function takes 80% of the run time, even a modest improvement there matters far more.
Define a target first
"Make it faster" cannot be finished. A target tells you when to stop. Good targets name a quantity, a workload, and a limit:
- The nightly report finishes in under 10 minutes on the production-sized input.
- The API endpoint answers in under 200 ms for 95% of requests.
- The import job stays under 2 GB of memory.
If the program already meets the target, the correct amount of optimization is none.
Measure a baseline
A baseline is a measurement of the current code on a realistic workload. Without it you cannot tell whether a change helped. Three habits make a baseline trustworthy:
- Use realistic input. A list of 10 items can hide a problem that appears with 10 million.
- Repeat the measurement. Run times vary because of other processes, caching, and CPU frequency changes. The minimum of several runs is usually the most stable figure, because noise only adds time.
- Record the result, along with the Python version and machine, so you can compare later.
Here is a minimal baseline using the standard library. The next chapter covers perf_counter and timeit properly.
import time
def build_report(n):
rows = []
for i in range(n):
rows.append(f"row {i}: {i * i}")
return "\n".join(rows)
start = time.perf_counter()
report = build_report(200_000)
elapsed = time.perf_counter() - start
print(f"build_report took {elapsed:.3f}s")Run it a few times. The numbers will differ slightly, and that spread is normal.
Two kinds of measurement
Timing tells you how long something takes. Profiling tells you where the time goes. You need both, in this order.
| Tool type | Question it answers | Example |
|---|---|---|
| Timer | How long does this snippet or program take? | `time.perf_counter`, `timeit` |
| Profiler | Which functions or lines use the time? | `cProfile`, `py-spy` |
| Memory profiler | Which lines hold the memory? | `tracemalloc` |
Start with a timer to get the baseline. Use a profiler to find the hot spot (the code that accounts for most of the cost). Then change that code and use the timer again to confirm the gain.
Common mistakes
- Changing several things at once. If the program gets faster, you do not know which change helped. If it gets slower, you do not know which one hurt.
- Measuring the wrong input. A fast result on toy data says little about production data.
- Trusting a single run. One timing can be off by a large margin from background load.
- Ignoring correctness. A faster program that returns wrong results is not an improvement. Keep tests running through every change.
- Optimizing the code you find interesting instead of the code the profiler points to.
What comes next
The following chapters build the toolkit in order: timing snippets, profiling whole programs, reading the output, and then the fixes that usually pay off.
Exercise
A function takes 4% of your program's total run time. You rewrite it to run 5 times faster. About how much faster does the whole program get, and what should you do instead?
Show answer
The function's cost drops from 4% to 0.8%, so the whole program saves about 3.2% of its run time. This is too small to notice. Instead, profile the program to find the code that takes most of the time and work on that, after setting a target so you know when to stop.
Exercise
Why is it better to change only one thing between measurements?
Show answer
With one change per measurement, any difference in timing can be credited to that change. With several changes you cannot tell which helped, which hurt, or whether they cancelled each other out.