Sub topic 2
Timing code reliably
This chapter assumes you know basic Python, can work with pandas DataFrames and Series, and have seen NumPy arrays. You will learn to measure how long a pandas operation takes so that you can trust the number.
Why one measurement is not enough
A single run of a piece of code gives a noisy number. The first run may include one-time costs such as loading modules or filling caches. Other programs on your machine also compete for the CPU. If you compare two versions of code using one run each, you can pick the wrong winner.
Reliable timing follows three rules:
- Use a clock made for measuring intervals.
- Repeat the measurement and look at the best or the median result.
- Time only the work you care about, not setup such as building the data.
Timing with perf_counter
time.perf_counter() is a high-resolution clock that only moves forward. Call it before and after the code, then subtract. Do not use time.time() for this, because it follows the system clock, which can be adjusted.
The example below compares a Python loop over rows with one vectorized multiplication.
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),
})
start = perf_counter()
totals = [row.price * row.qty for row in df.itertuples(index=False)]
print(f"itertuples loop: {perf_counter() - start:.3f}s")
start = perf_counter()
totals_vec = df["price"] * df["qty"]
print(f"vectorized: {perf_counter() - start:.3f}s")The data is created before the first start, so the timings cover only the two calculations. The exact numbers depend on your machine. Expect the vectorized line to be much faster, often by one to two orders of magnitude.
Repeating the measurement
A helper that runs the code several times makes the result more stable. Report the minimum, because slowdowns from other processes only add time. They never make your code faster than it really is.
from time import perf_counter
def best_of(func, repeats=5):
times = []
for _ in range(repeats):
start = perf_counter()
func()
times.append(perf_counter() - start)
return min(times)
print(f"{best_of(lambda: df['price'] * df['qty']):.5f}s")Timing in a notebook with %timeit
In Jupyter or IPython, %timeit does the repeating for you. It chooses how many loops to run, then reports the mean and standard deviation across several runs.
%timeit df["price"] * df["qty"]Use %%timeit at the top of a cell to time the whole cell. Anything before the cell magic on the same cell is not allowed, so create your data in an earlier cell. Outside notebooks, the standard library's timeit module offers the same behavior.
Common timing errors
- Timing data creation. Building or loading the DataFrame is a separate cost. Keep it outside the timed region.
- Testing on tiny data. A 100-row frame hides costs that appear at 10 million rows. Time at realistic sizes.
- Forgetting that code changes the data. If the timed code modifies
dfin place, the second run works on different input. Copy the frame inside the timed function when needed. - Trusting one run. Repeat, and compare the minimum or median.
- Comparing different work. Both versions must produce the same result. Chapter 6 shows how to check that.
How the pieces fit
Exercise
You time a function once with perf_counter and get 0.80s. After a second run you get 0.52s. Give two likely reasons for the difference, and say what you would do to get a trustworthy number.
Show answer
Likely reasons: the first run paid one-time costs such as warming caches or importing modules, and other processes on the machine used CPU time during the first run. Repeat the measurement several times, keep data creation outside the timed region, and report the minimum or median, or use %timeit.
Exercise
Why is time.perf_counter() preferred over time.time() for measuring how long code takes?
Show answer
perf_counter is a high-resolution clock that never goes backward, so it suits measuring intervals. time.time() follows the system clock, which can be adjusted and has lower resolution on some systems.