Sub topic 3
Profiling a Pipeline to Find the Bottleneck
This chapter assumes you can write Python functions, use pandas DataFrames (column selection, filtering, groupby, merge), and have used time.perf_counter to time a single statement. Timing tells you how long something took. Profiling tells you where the time went inside it. That is what you need when a pipeline has many steps and you don't know which one to fix.
Why timing is not enough
Suppose a function takes 12 seconds. A stopwatch around the whole call shows only the total. You could add a perf_counter pair around every line, but this is tedious. It also changes the code you are trying to understand, and you still have to guess which lines to wrap.
A profiler records the time of every function call while your code runs. It then reports a table you can sort by cost. The Python standard library includes cProfile, a deterministic profiler. Deterministic means it hooks every function call and return, rather than sampling the program at intervals.
Setting up a pipeline to profile
The examples below use a small pipeline on synthetic data. The frame is built once and reused.
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),
})The pipeline copies the frame, computes a total, builds a text label, and sums totals per quantity.
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()Running cProfile
Use cProfile.Profile as a context manager (Python 3.8 and later). Then hand the collected data to pstats to sort and print it.
import cProfile
import pstats
with cProfile.Profile() as profiler:
result = pipeline(df)
pstats.Stats(profiler).sort_stats("cumulative").print_stats(10)The output is a table with one row per function. Only the ten rows with the largest cumulative time are printed. The exact numbers vary by machine, but the layout is always the same.
Reading the profile table
Each row has these columns.
| Column | Meaning |
|---|---|
| `ncalls` | How many times the function was called. A value like `3/1` means 3 calls in total, 1 of them not recursive. |
| `tottime` | Seconds spent inside the function itself, excluding functions it called. |
| `percall` (first) | `tottime` divided by `ncalls`. |
| `cumtime` | Seconds spent in the function plus everything it called. |
| `percall` (second) | `cumtime` divided by the number of primitive calls. |
| `filename:lineno(function)` | Where the function is defined. |
The two time columns answer different questions.
cumtimeshows which high-level step is expensive. Your ownpipelinefunction will always be at the top, because it contains everything. Look at the rows just below it.tottimeshows where time is spent doing work directly. Sorting by it points at leaf functions, such as a low-level copy or a string conversion, that do the real work.
A useful routine is to sort by cumulative first to find the expensive step, then by tottime to see what is expensive inside it.
stats = pstats.Stats(profiler)
stats.sort_stats("cumulative").print_stats(10)
stats.sort_stats("tottime").print_stats(10)A profile has noise from pandas internals
A pandas call like out["qty"].astype(str) passes through many internal layers: indexing, block management, dtype checks. These all appear in the table. Don't try to understand every row. Use these habits:
- Find your own function names first. They have your file name, or
<stdin>or<ipython-input-...>in an interactive session. - Read down from there to the first pandas rows with a large
cumtime. Their names (astype,groupby,_cython_agg_general,copy) tell you which of your lines is responsible. - Ignore rows with tiny
cumtime, even ifncallsis large.
A very large ncalls on a small function is also a signal. If you see iterrows or a lambda called 200,000 times, you have found a row-wise loop. The next chapter explains why those are slow.
Filtering the output
print_stats accepts restrictions. A string is treated as a regular expression matched against the file and function name, and a number below 1 is treated as a fraction of the rows.
stats.sort_stats("cumulative").print_stats("pandas", 0.2)This keeps rows from files whose path contains pandas, and then shows the top 20 percent of those. You can also inspect callers and callees of one function.
stats.print_callers("astype")
stats.print_callees("pipeline")print_callees("pipeline") lists what pipeline calls and how much time each call took. This is often the quickest way to turn a flat table into a breakdown by step.
Saving a profile and viewing it later
For long runs, save the data to a file and analyze it afterward. You can also run an entire script under the profiler from the command line.
profiler.dump_stats("pipeline.prof")
loaded = pstats.Stats("pipeline.prof")
loaded.strip_dirs().sort_stats("cumulative").print_stats(10)# Command line equivalent, shown as a comment:
# python -m cProfile -o pipeline.prof my_script.pystrip_dirs() removes long directory prefixes, which makes the table easier to read. Because the file is only data, you can compare profiles from before and after a change.
Step-level timing as a complement
Sometimes a profile is too detailed. A coarse alternative is to time each named step of your pipeline with a small helper. This works well when the pipeline is already split into functions.
from contextlib import contextmanager
from time import perf_counter
@contextmanager
def timed(name):
start = perf_counter()
try:
yield
finally:
print(f"{name:<12} {perf_counter() - start:.4f}s")
out = df.copy()
with timed("total"):
out["total"] = out["price"] * out["qty"]
with timed("label"):
out["label"] = out["qty"].astype(str) + "-items"
with timed("groupby"):
summary = out.groupby("qty")["total"].sum()This gives one line per step, with no pandas internals. Use cProfile when you don't yet know which step is slow. Use a helper like this once you do know and want a clean before-and-after comparison.
How the profiler distorts timing
cProfile adds overhead to every Python function call, so the totals are larger than an unprofiled run. The overhead is not spread evenly.
- Code that makes many small Python calls (a row-wise loop) is slowed a lot.
- Code that spends its time in one large compiled operation (a vectorized multiply) is slowed very little.
As a result, a profile can make loopy code look worse than it really is relative to vectorized code. Use the profile to rank steps and find the culprit. Then measure the real gain with perf_counter or %timeit on the unprofiled code.
Common mistakes
- Profiling a cold, tiny sample. If the data is much smaller than production data, the ranking of steps may differ. Some costs grow with row count, and others are fixed. Profile with realistic sizes.
- Profiling a single run with a one-time cost. The first call may include imports or caches being built. Run the pipeline once before profiling if that is not what you want to measure.
- Optimizing the top row of a
tottimesort blindly. A function with hightottimemay be a necessary internal step. Trace it back to your own line withprint_callersbefore changing code. - Fixing a step that takes 2% of the total. Even making it instant saves 2%. Work on the step with the largest share.
- Changing several things at once. You can't tell which change helped. Change one step, re-time, then continue.
Putting it together
For any slow pipeline, follow this sequence:
- Build or load data at a realistic size.
- Run the pipeline once to warm up, then once under
cProfile. - Sort by
cumulative, and find the first of your own steps with a large share. - Check
print_callersorprint_calleesto confirm which line is the cause. - Make one change.
- Re-time without the profiler, and compare the result with the original.
- Profile again, since the next bottleneck may now be a different step.
Exercise
You profile a pipeline and sort by tottime. The top row is a pandas internal function, copy, taking 40% of the time. Your code calls df.copy() in five places. What should you do next, and why is the tottime row alone not enough to act on?
Show answer
Run stats.print_callers("copy") to see which of your five call sites accounts for the time. The tottime row shows that copying is expensive overall, but not which of your lines triggers it. Once you know the call site, remove or move the unnecessary copies one at a time, re-time without the profiler after each change, and check that the result is unchanged.
Exercise
A step shows a cumtime of 8 seconds under cProfile, but when you time it with perf_counter and no profiler, it takes 3 seconds. Does this mean the profile is wrong? Which number should you use to judge your fix?
Show answer
The profile is not wrong. The profiler adds overhead to every function call, especially in code with many small calls, so profiled times are inflated. Use the profile to rank steps and pick the target. Use the unprofiled perf_counter (or %timeit) number to judge whether your fix helped.
Exercise
Write code that runs pipeline(df) under cProfile and prints only the five rows with the largest tottime.
Show answer
import cProfile, pstats with cProfile.Profile() as profiler: pipeline(df) pstats.Stats(profiler).sortstats("tottime").printstats(5)