Sub topic 1
Measure first: why guessing about performance fails
Most slow pandas code is slow for reasons its author did not predict. This chapter explains why guessing fails and gives you a repeatable process to replace it. The later chapters supply the tools and the fixes. This one sets the habit that makes them useful.
Prerequisites
This chapter assumes you can:
- Write Python functions and list comprehensions.
- Select columns, filter rows, and use
groupbyandmergeon a pandas DataFrame. - Understand that NumPy arrays support element-wise operations, such as multiplying two arrays.
You need numpy and pandas installed. Every example runs as shown, but the timings will differ on your machine.
The problem with intuition
Developers often "know" which line is slow. They are wrong often enough that experienced engineers treat such beliefs as hypotheses to test. Four things make pandas especially hard to judge by eye.
- Layers hide the real work. One line such as
df.groupby("city")["price"].sum()can trigger hashing, sorting, copying, and compiled loops. The line looks cheap or expensive depending on what you assume is inside it. - Cost depends on the data, not the code. The same expression behaves differently on 1,000 rows and on 10 million. It also differs between a column of integers and a column of Python strings, and between a few unique keys and millions of them.
- Python-level and compiled work differ by orders of magnitude. An operation that runs inside NumPy's compiled code can be dozens or hundreds of times faster per element than the same logic in a Python loop. Visually similar lines can fall on either side of that gap.
- Memory matters as much as arithmetic. Copies, large temporary arrays, and object columns slow things down in ways no single line reveals.
Guessing fails in two ways. You may optimize a step that barely matters, which adds complexity and gains nothing. Or you may "fix" something and make it slower, because your mental model was wrong.
A worked example: four steps, one surprise
The script below times four common operations on the same frame. Run it before reading the discussion, and write down which step you expect to be slowest.
import numpy as np
import pandas as pd
from time import perf_counter
rng = np.random.default_rng(0)
n = 500_000
df = pd.DataFrame({
"price": rng.random(n),
"qty": rng.integers(1, 10, n),
"city": rng.choice(["Oslo", "Lima", "Pune", "Cairo"], size=n),
})
def timed(label, func):
start = perf_counter()
result = func()
print(f"{label:<22}{perf_counter() - start:.4f}s")
return result
timed("price * qty", lambda: df["price"] * df["qty"])
timed("city.str.upper()", lambda: df["city"].str.upper())
timed("groupby city sum", lambda: df.groupby("city")["price"].sum())
timed("sort_values price", lambda: df.sort_values("price"))The helper timed runs a function, prints the elapsed wall-clock time, and returns the result. perf_counter is a clock meant for measuring short intervals. It is monotonic, so it never jumps backwards.
On most machines the multiplication finishes far faster than the other three, often by a factor of ten or more. The string method and the sort cost much more, even though .str.upper() reads like a trivial cleanup step. If you expected the groupby to be the worst, the measurement corrects you. The exact ranking depends on your hardware, your pandas version, and the column types. That dependence is the point: the numbers only count on your data.
Where the time goes: the share-of-runtime idea
A pipeline's total time is the sum of its steps. Speeding up one step can only remove that step's share. If a step takes a fraction p of the total runtime, then even making it instantaneous gives a maximum speedup of 1 / (1 - p).
| Share of total runtime | Best possible overall speedup if the step becomes free |
|---|---|
| 5% | about 1.05x |
| 25% | about 1.33x |
| 50% | 2x |
| 90% | 10x |
Suppose a pipeline takes 100 seconds. One loop takes 5 seconds, and a merge takes 90 seconds. Rewriting the loop perfectly saves 5 seconds. Making the merge twice as fast saves 45. Only measurement shows which one you have.
The process in five rules
- Define "fast enough" first. A nightly job that runs in 4 minutes may need no work. A dashboard query that takes 4 seconds may need a lot. Without a target, you cannot tell when to stop, and you will keep optimizing past the point of value.
- Measure the whole pipeline before any part. The total is your baseline. Every later claim of "faster" is a comparison against it.
- Locate the bottleneck, then touch only that. Profiling, covered in a later chapter, ranks steps by cost. Work from the top of that list.
- Change one thing at a time. If you rewrite three steps together and the pipeline speeds up, you cannot tell which change helped or whether one hurt.
- Verify the output after each change. A fast wrong answer is a regression, not an optimization. A later chapter covers result checks in detail.
Common errors when measuring
Bad measurements are worse than none, because they give false confidence. These mistakes appear most often.
- Timing once. A single run includes noise from other processes, CPU frequency changes, and garbage collection. Repeat the measurement and compare the best or median run. The next chapter covers
%timeitand related tools. - Including setup in the timed region. If you time data loading together with the operation you are testing, loading may dominate and hide the difference.
- Testing on toy data. A 1,000-row sample often shows no difference, or the opposite one. Per-call overhead dominates at small sizes, while algorithmic cost dominates at large sizes. Test at the size you will run in production, or at least in the same order of magnitude.
- Comparing different inputs. If version A runs on sorted data and version B on shuffled data, you measured the data, not the code.
- Ignoring warm-up. The first call can pay for imports, lazy initialization, or cold caches. Later calls may be faster for reasons unrelated to your change.
- Measuring time but not memory. A version that is 20% faster but needs three times the memory may crash on a larger input.
- Trusting a notebook's feel. Perceived responsiveness in a notebook includes display rendering and other cells. Use a clock.
Recording a baseline
A baseline is the measurement you compare every later change against. Keep it with the code. The helper below runs a function several times and reports the best and median times. It is a small preview of the more careful tools in the next chapter.
import statistics
from time import perf_counter
def benchmark(func, repeats=5):
times = []
for _ in range(repeats):
start = perf_counter()
func()
times.append(perf_counter() - start)
return min(times), statistics.median(times)
best, median = benchmark(lambda: df.sort_values("price"))
print(f"best {best:.4f}s, median {median:.4f}s")The minimum approximates the run with the least interference. The median shows typical behavior. If the two differ a lot, your machine is noisy and the comparison is unreliable. Close other programs and run it again.
Write down four things next to your baseline: the number of rows and columns, the pandas and Python versions, the machine you ran it on, and the command used. Without them, you cannot reproduce the number a month later.
Typical wrong guesses
The table lists beliefs that regularly turn out false, with what to do instead of acting on them.
| Belief | Why it can be wrong | What to do |
|---|---|---|
| "Loops are always the problem." | The loop may run 50 times over a small frame while a merge takes most of the runtime. | Profile first, then decide. |
| "This looks clever, so it must be fast." | A dense one-liner can hide copies or Python-level calls. | Time it against the plain version. |
| "Vectorized code is always faster." | Vectorized code that builds huge temporary arrays can be slower or exhaust memory. | Measure time and memory. |
| "My small test proves it." | Overhead dominates at small sizes. | Retest at realistic size. |
| "Less code means faster code." | Line count says little about runtime. | Compare measured times. |
When to stop
Stop when you reach the target from rule 1. Also stop when the largest remaining step is below a few percent of total runtime, because further work cannot pay off much. Finally, stop if the next improvement needs a different tool, such as a database or a distributed engine. That decision comes at the end of this tutorial.
Exercises
Exercise
A pipeline takes 200 seconds. A loop you want to rewrite accounts for 10 seconds of that. If your rewrite makes the loop take no time at all, what is the new total runtime and the overall speedup?
Show answer
The new total is 190 seconds. The speedup is 200 / 190, about 1.05x. Even a perfect rewrite of a step that is 5% of runtime gains only about 5%, so profile first and work on a larger step.
Exercise
A colleague reports that version B of a function is "twice as fast" as version A. They timed each once on a 2,000-row sample, with B run second in the same notebook session. Name three problems with this measurement and say how to fix each.
Show answer
(1) One run each is noisy, so repeat several times and compare the best or median. (2) A 2,000-row sample may not reflect production size, so repeat the test on data of realistic size. (3) B ran second, so caches and warm-up effects may have helped it, so alternate the order or discard a warm-up run. Also check that both versions got identical input and return identical results.