Sub topic 3
Profiling a Pipeline to Find the Bottleneck
This chapter assumes you can write basic Python functions, select columns and use groupby in pandas, and time code with perf_counter. Timing tells you how long a whole operation takes. Profiling tells you which step inside it takes the time.
Why timing is not enough
A pipeline often has several steps: add columns, build labels, aggregate. If the whole pipeline takes 2 seconds, you still do not know which line to fix. Optimizing the wrong step wastes effort and can make the code harder to read for no gain.
A profiler runs your code and records how many times each function was called and how long it spent there. Python ships with one, cProfile.
Profiling a pipeline with cProfile
The example builds a data set, defines a three-step pipeline, and profiles one call.
import cProfile
import pstats
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
df = pd.DataFrame({
"price": rng.random(200_000),
"qty": rng.integers(1, 10, 200_000),
})
def pipeline(df):
out = df.copy()
out["total"] = out["price"] * out["qty"]
out["label"] = out["qty"].astype(str) + "-items"
return out.groupby("qty")["total"].sum()
with cProfile.Profile() as profiler:
result = pipeline(df)
pstats.Stats(profiler).sort_stats("cumulative").print_stats(10)cProfile.Profile() used as a context manager records everything that runs inside the with block. pstats.Stats formats the records. Sorting by "cumulative" and printing 10 entries shows the ten calls with the largest total time.
Reading the output
Each row of the report has these columns:
| Column | Meaning |
|---|---|
| `ncalls` | How many times the function was called |
| `tottime` | Time spent in the function itself, excluding functions it called |
| `cumtime` | Time in the function plus everything it called |
| `percall` | The time divided by the number of calls (shown for both `tottime` and `cumtime`) |
| `filename:lineno(function)` | Where the function is defined |
Start with cumtime. The top row is usually pipeline itself, because it contains everything. Read down to the first pandas calls and compare their cumtime values. A step whose cumtime is a large share of the pipeline row is your candidate.
Then look at tottime. A function with high cumtime but low tottime mostly waits on its callees, so look further down the call chain. A function with high tottime does its own work, and that work is what you can change.
Common mistakes
- Profiling tiny data. With 100 rows, fixed overhead dominates and the ranking can differ from production. Use a realistic size.
- Profiling once and trusting the numbers. Run it twice. The first run can include one-time costs such as imports or cache warm-up.
- Reading only the top row. The top row is the whole pipeline. The useful information is a few lines lower.
- Fixing everything the profiler lists. Change the dominant step, then profile again. The ranking often changes after one fix.
Profiling whole steps by hand
If the report is too noisy, time each step directly. This is quick and shows a clear ranking.
from time import perf_counter
out = df.copy()
start = perf_counter()
out["total"] = out["price"] * out["qty"]
print(f"total: {perf_counter() - start:.4f}s")
start = perf_counter()
out["label"] = out["qty"].astype(str) + "-items"
print(f"label: {perf_counter() - start:.4f}s")
start = perf_counter()
grouped = out.groupby("qty")["total"].sum()
print(f"groupby: {perf_counter() - start:.4f}s")On most machines the string label step is the slowest here, because it creates 200,000 Python string objects, while the arithmetic and groupby run in compiled code. Your numbers will differ, and that is the reason to measure instead of assume.
Exercise
A cProfile report shows pipeline with a cumtime of 1.9 s. A pandas function called inside it has a cumtime of 1.6 s but a tottime of 0.01 s. Should you try to optimize that function's own code? What should you do next?
Show answer
No. The low tottime means the function does almost no work itself. It spends its time in functions it calls. Look at the rows below it in the report to find the callee with a high tottime, and focus on that step or on how your code calls it.