Sub topic 1
Why You Measure Before You Optimize
Most slow Python programs are slow in one or two places, and those places are rarely where you would guess. This chapter explains why you should measure before changing code, what a useful measurement looks like, and which habits make optimization work reliable. The later chapters give you the tools: timing, profilers, and fixes. This one sets the rules for using them.
Prerequisites
This chapter assumes you can:
- Write and run Python functions, loops, and modules.
- Use lists, dicts, and sets.
- Run a script from a terminal.
- Install packages with pip.
You do not need any profiling experience. The chapter uses only the standard library.
The working model
Optimization is an experiment, not a rewrite. Each round follows the same loop:
- Define a target: how fast is fast enough, on what input, on what machine.
- Measure a baseline: how fast it is now.
- Find the bottleneck: the part of the program that dominates the time.
- Change one thing.
- Measure again and compare with the baseline.
- Stop when you reach the target.
Skipping the measurement steps is the most common mistake. Without a baseline you cannot tell whether a change helped. Without a bottleneck you are guessing where to work.
Start with a performance target
"Make it faster" is not a goal you can finish. A target names a number, an input, and an environment. These are examples:
- The nightly import must finish in under 30 minutes on the production server with a full day of data.
- The
/searchendpoint must answer in under 200 ms at the 95th percentile. - The script must process a 2 GB log file using less than 1 GB of memory.
A target does three things:
- It tells you when to stop. Code that is already fast enough does not need more work, and every optimization adds some complexity.
- It tells you what to measure. Wall-clock time, memory, and latency under load are different quantities, and fixes for one can hurt another.
- It tells you which input to use. A function that is quick on 100 items may be slow on 1,000,000. Measure with data that is the size and shape of the real data.
If you have no target, write one down anyway, even a rough one. You can revise it later.
Why intuition fails
Developers are often wrong about where time goes. Three effects explain most of the surprises.
First, the cost of a line depends on how often it runs. A statement that costs a microsecond and runs 50 million times costs 50 seconds. An expensive-looking call that runs once barely registers.
Second, Python hides costs behind simple syntax. x in some_list scans the list. text += piece can copy the whole string. A dict lookup is cheap and a list lookup is not, but the two look almost the same on the page.
Third, time is often spent outside your own code: reading files, waiting on the network or a database, and importing modules. Rewriting your loop does nothing for a program that spends 90% of its time waiting for a query.
The limit on what one fix can do
A bottleneck's share of total runtime caps the gain from fixing it. This is Amdahl's law. If a part takes a fraction p of the runtime and you make it s times faster, the whole program speeds up by:
speedup = 1 / ((1 - p) + p / s)| Share of runtime (p) | Speedup of that part (s) | Whole-program speedup |
|---|---|---|
| 5% | 10x | about 1.05x |
| 5% | infinite | at most 1.05x |
| 50% | 10x | about 1.82x |
| 80% | 4x | 2.5x |
| 95% | 10x | about 6.9x |
Making a 5% part ten times faster saves almost nothing, even if the work took a week. The 95% part is worth the effort. A profiler tells you which row of this table you are in.
A worked example: time the stages first
You do not need a profiler to take a first measurement. Wrapping each stage of a program in a timer shows where the time goes. The helper below uses time.perf_counter, a clock meant for measuring short intervals. The next chapter covers it in detail.
import time
from contextlib import contextmanager
timings = {}
@contextmanager
def stage(name):
start = time.perf_counter()
try:
yield
finally:
timings[name] = time.perf_counter() - start
def load_records(n):
return [{"id": i, "name": f"user{i}"} for i in range(n)]
def find_duplicates(ids):
seen = []
duplicates = []
for value in ids:
if value in seen:
duplicates.append(value)
else:
seen.append(value)
return duplicates
def render(records):
return "\n".join(f"{r['id']},{r['name']}" for r in records)
def main():
with stage("load"):
records = load_records(20_000)
with stage("dedupe"):
ids = [r["id"] % 15_000 for r in records]
duplicates = find_duplicates(ids)
with stage("render"):
text = render(records)
total = sum(timings.values())
for name, seconds in timings.items():
print(f"{name:8s} {seconds:8.4f}s {seconds / total:6.1%}")
print(f"duplicates: {len(duplicates)}, output chars: {len(text)}")
if __name__ == "__main__":
main()Run it a few times. The exact numbers depend on your machine, but the shape is stable: dedupe takes nearly all the time, and load and render together take a small fraction of it. The reason is that value in seen scans a list, so the work grows with the square of the input size.
Now compare two reactions:
- A developer who guesses might rewrite
renderorload_recordswith a clever trick. Those stages are only a few percent of the total, so the whole program barely changes, as the table above predicts. - A developer who measured goes straight to
find_duplicates. Using a set forseenremoves the repeated scans. A later chapter covers that fix in detail.
The measurement took a few minutes. It prevented hours of work on the wrong code.
Common errors
These mistakes appear again and again. Knowing them in advance saves time.
- Optimizing without a baseline. If you did not record the starting number, "it feels faster" is the only evidence you have. Save the baseline output before you edit anything.
- Changing several things at once. If you swap an algorithm, add a cache, and rewrite a loop, you cannot tell which change helped and which hurt. Change one thing per measurement.
- Measuring once. Timings vary from run to run because of other processes, CPU frequency changes, and cold caches. Repeat the measurement, and compare the best or the median of several runs, not a single sample.
- Measuring tiny inputs. Cost that grows with input size hides in small tests. Use realistic data.
- Measuring the wrong thing. The first run may include imports, disk caching, or one-time setup. Decide whether you are measuring startup or steady state, and keep that choice fixed.
- Trusting a different environment. A laptop, a CI runner, and a production server differ in CPU, memory, and load. Final numbers should come from an environment close to the one that matters.
- Breaking correctness. A faster function that returns wrong results is worse than a slow one. Keep tests running, and check that outputs are unchanged after each optimization.
- Treating the profiler as an oracle. Profilers add overhead and can distort a program's timing. Use them to find where to look, then confirm a fix with a plain timing of the unprofiled code.
What optimization costs
Faster code is not free. Caches use memory and can return stale results. Parallel code is harder to debug. Native extensions add build steps. Clever code is harder for the next reader to understand.
For this reason, order your options from cheapest to most expensive in terms of complexity:
- Check whether the work is needed at all.
- Fix the algorithm or data structure.
- Use idiomatic, built-in operations.
- Cache repeated results.
- Use vectorized libraries such as NumPy.
- Use threads or processes.
- Use native code.
This chapter's loop tells you when to stop. If the target is met after step 2, do not continue to step 5. The rest of this tutorial follows roughly this order.
What comes next
The next chapter shows how to time snippets reliably with perf_counter and timeit. After that you will profile a whole program with cProfile, read its output, and use the results to choose between the fixes listed above.
Exercise
A profile shows that function render takes 10% of a program's total runtime. You rewrite it and it becomes 10 times faster. Using Amdahl's law, what is the approximate speedup of the whole program? Would you say the work was well targeted?
Show answer
speedup = 1 / ((1 - 0.10) + 0.10 / 10) = 1 / (0.90 + 0.01) = 1 / 0.91, which is about 1.10x. The whole program runs only about 10% faster, even though the function became ten times faster. Even an infinitely fast render would cap the gain at about 1.11x. The work was poorly targeted unless the target was nearly met already. The larger bottleneck should be examined first.
Exercise
Name three problems with this workflow: "I rewrote the loop, added a cache, and switched to a set. It feels faster, so I committed it."
Show answer
There is no performance target, so there is no way to know whether the work is finished. There is no baseline measurement, so "feels faster" has no number to back it. Three changes were made at once, so you cannot tell which helped, which did nothing, and which added complexity or risk for no gain. Correctness was not checked either. A good answer also mentions that a single unrepeated timing is unreliable.