Sub topic 1
Measure first: why guessing about performance fails
Prerequisites
This chapter assumes you can read basic Python, including functions and list comprehensions. It also assumes you know how to select columns, filter rows, group, and merge in pandas, and that you understand NumPy arrays and element-wise operations. No profiling experience is needed.
Why intuition misleads
Most slow pandas code is slow in one or two places. Developers often guess which places, and the guesses are often wrong. Three habits cause most of the misses:
- Blaming the step that looks complicated, such as a groupby, when a simple-looking string conversion costs more.
- Optimizing the step you know best, because you know how to fix it.
- Trusting advice that is true in general but not for your data size, dtypes, or machine.
Speeding up a step that takes 2% of the run time can save at most 2%. Finding the step that takes 70% is what pays off. Measuring is how you find it.
The measure-change-verify loop
Treat every optimization as a small experiment. You measure, change one thing, measure again, and check that the output is unchanged.
The loop gives you three things. A baseline tells you whether a change helped. Changing one thing at a time tells you which change was responsible. The result check catches optimizations that are fast because they are wrong.
A first measurement
The script below builds a small pipeline and times each step separately. It uses time.perf_counter, a high-resolution clock meant for measuring durations.
import numpy as np
import pandas as pd
from time import perf_counter
rng = np.random.default_rng(0)
df = pd.DataFrame({
"price": rng.random(200_000),
"qty": rng.integers(1, 10, 200_000),
})
def timed(label, func):
start = perf_counter()
result = func()
print(f"{label:<14} {perf_counter() - start:.4f}s")
return result
timed("multiply", lambda: df["price"] * df["qty"])
timed("string label", lambda: df["qty"].astype(str) + "-items")
timed("groupby sum", lambda: df.groupby("qty")["price"].sum())Run it and compare the three lines. On most machines the string step is the slowest by a wide margin, even though it looks like the simplest. Your exact numbers will differ, and that is the point: the ranking on your data and hardware is the only ranking that matters.
Common errors when measuring
- Timing once. A single run includes noise from other processes, caches, and memory allocation. Repeat the measurement and compare several runs. The next chapter covers
%timeitand repeated timing. - Timing at the wrong scale. A trick that wins on 1,000 rows may lose on 10 million, or the reverse. Measure on data close to production size.
- Measuring only the total. A total of 12 seconds tells you there is a problem but not where it is. Per-step timing and profiling, covered in the following chapters, answer that.
- Changing several things at once. If the code gets faster, you will not know which change did it. If it gets slower, you will not know which one to undo.
- Skipping the correctness check. An optimized version that returns different numbers is a bug, not a speedup.
What comes next
The following chapters build the tools for each stage of the loop. You will time code reliably, then profile a pipeline to locate its bottleneck. After that you will learn the fixes for the most common causes: row-wise loops, poor dtypes, repeated concatenation, and wasteful file loading.
Exercise
A pipeline takes 10 seconds. You time its steps and find that step A takes 6 seconds, step B takes 3 seconds, and step C takes 1 second. You can make exactly one step twice as fast. Which should you pick, and what total time do you expect afterward?
Show answer
Pick step A. Halving it saves 3 seconds, so the pipeline takes about 7 seconds. Halving B saves 1.5 seconds (8.5 total) and halving C saves 0.5 seconds (9.5 total). Per-step timing is what makes this choice possible.
Exercise
A teammate says "iterrows is always the bottleneck, so I rewrote it." The pipeline runtime did not change. List two likely reasons.
Show answer
The loop was not where most of the time went, so speeding it up could not change the total much. Or the measurement was unreliable, for example one noisy run before and one after, or a different data size. Timing each step before changing anything, and repeating runs, would have shown this.