Sub topic 1
Measure First: Why Guessing About Performance Fails
Prerequisites
This chapter assumes basic Python, pandas DataFrames and Series, groupby, and simple NumPy array operations.
Measure first
Performance work starts with evidence. A slow-looking line may run rarely, while an ordinary-looking transformation may run millions of times. Optimizing the wrong step adds complexity without improving the program.
Measure a representative dataset on the machine where the code will run. Record both run time and memory when memory pressure might affect performance. Keep the original result so you can compare it with each optimization.
Timing code reliably
Use time.perf_counter() for timings inside a Python script. It uses a high-resolution clock. Run the operation several times and compare repeated measurements rather than trusting one result.
import pandas as pd
from time import perf_counter
df = pd.DataFrame({"price": range(100_000), "qty": 2})
def calculate(frame):
return frame["price"] * frame["qty"]
times = []
for _ in range(5):
start = perf_counter()
calculate(df)
times.append(perf_counter() - start)
print(f"median: {sorted(times)[len(times) // 2]:.6f}s")In a notebook, %timeit calculate(df) is convenient because it repeats the operation automatically. Avoid timing data loading, printing, or setup unless those costs are part of the problem.
Profile the pipeline
Timing tells you how long the whole operation takes. Profiling shows where that time goes. cProfile records function calls, and pstats sorts them by cumulative time, including time spent in called functions.
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(frame):
out = frame.copy()
out["total"] = out["price"] * out["qty"]
out["label"] = out["qty"].astype(str)
return out.groupby("qty")["total"].sum()
with cProfile.Profile() as profiler:
pipeline(df)
pstats.Stats(profiler).sort_stats("cumulative").print_stats(10)Why `iterrows` and Python loops are slow
A row-wise loop crosses between pandas and Python for every row. Each row may become a temporary Series, with repeated indexing and type handling. Vectorized operations work on whole columns through optimized NumPy or pandas code.
# Slow: Python work for every row
for index, row in df.iterrows():
df.loc[index, "total"] = row["price"] * row["qty"]
# Usually faster: one column-wise operation
df["total"] = df["price"] * df["qty"]Exercise
Why should you profile before replacing a loop?
Show answer
Profiling identifies whether that loop dominates runtime, so you optimize a measured bottleneck instead of adding complexity to an unimportant step.