Sub topic 2
Timing Code Reliably
This chapter assumes you know basic Python (functions, list comprehensions), can select, filter, group and merge pandas DataFrames, and understand NumPy's element-wise operations. You will learn how to time pandas code so the numbers can be trusted. The next chapter uses profiling to find where time goes inside a pipeline. Timing comes first because you need a trustworthy number to know whether any change helped.
Why a single timing is not enough
A single run of a piece of code gives a noisy number. Several things disturb it:
- The operating system schedules other processes on the same CPU core.
- The CPU may change its clock speed as it warms up.
- The first call can pay one-time costs, such as importing a module or filling caches.
- Memory allocation patterns differ between runs.
A timing is therefore a sample from a distribution. To compare two versions of code, you need several samples and a summary that ignores outliers. The usual summary is the minimum, because noise only ever adds time. The fastest run is the one least disturbed by other activity.
Timing with time.perf_counter
time.perf_counter() returns a high-resolution clock value in seconds. Only the difference between two calls means anything. Use it instead of time.time(), which can jump when the system clock is adjusted.
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")This measures a Python loop over rows against a single vectorized multiplication. On most machines the loop takes tens to hundreds of milliseconds, and the vectorized line takes about a millisecond or less. Your exact numbers will differ. The ratio is what matters, and you should always measure it on your own data and hardware.
Pitfalls of a single perf_counter measurement
This pattern is quick, but it has weaknesses:
- One sample. Run the script twice and you will get two different numbers.
- Cold start. The first call may include warm-up work.
- Setup mixed with the work. If you build the data inside the timed region, you measure the setup too.
- Lazy or cached results. Some operations cache results, so a second call can be faster for reasons unrelated to your change.
Repeating measurements yourself
Wrap the work in a function and repeat it. Take the minimum, and also look at the spread.
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),
})
def best_of(func, repeats=7):
"""Return (min, median) wall time in seconds over several runs."""
func() # warm-up run, not recorded
times = []
for _ in range(repeats):
start = perf_counter()
func()
times.append(perf_counter() - start)
times.sort()
return times[0], times[len(times) // 2]
fast_min, fast_med = best_of(lambda: df["price"] * df["qty"])
print(f"min {fast_min * 1000:.2f} ms, median {fast_med * 1000:.2f} ms")The warm-up call absorbs one-time costs. If the minimum and the median are far apart, the machine was busy, and you should rerun the measurement.
Timing with the standard timeit module
Python's timeit module does this repetition for you, and it disables garbage collection during timing by default. That removes one source of random pauses. timeit.repeat returns a list of totals, one per repeat. Each total covers number calls of the statement, so divide by number to get the time per call.
import timeit
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),
})
runs = timeit.repeat(
stmt='df["price"] * df["qty"]',
globals=globals(),
repeat=5,
number=100,
)
per_call = min(runs) / 100
print(f"best per call: {per_call * 1000:.3f} ms")The globals=globals() argument lets the statement see your df. Without it, timeit runs the statement in an empty namespace and raises a NameError.
Timing in Jupyter with %timeit
In a notebook or IPython session, the %timeit magic command is the most convenient tool. It picks the number of loops automatically so the measurement takes a reasonable time, then reports the mean and standard deviation across several runs.
%timeit df["price"] * df["qty"]A typical output looks like this:
412 µs ± 8.1 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)Read it as: seven runs, each with 1,000 calls, and the mean time per call was 412 microseconds. A standard deviation that is small compared with the mean means the measurement is stable.
There are two forms:
| Form | Syntax | Times |
|---|---|---|
| Line magic | `%timeit expr` | Only the single line after it |
| Cell magic | `%%timeit` at the top of a cell | The whole cell |
With %%timeit, you can run setup in the first line, which is excluded from the timing only when it is on the same line as the magic. For example, %%timeit -n 10 -r 5 limits the measurement to 10 loops per run and 5 runs. The -o flag returns a result object, which lets you read best and average from code.
Use %timeit only in IPython and Jupyter. A plain .py script treats the % as a syntax error.
Keeping setup out of the timed region
Suppose you want to time a sort. Sorting in place changes the data, so repeated runs would sort already sorted data and look faster. Create fresh input for each run, and keep that cost out of the measurement.
import timeit
import numpy as np
import pandas as pd
rng = np.random.default_rng(1)
base = pd.DataFrame({"x": rng.random(1_000_000)})
def run_once():
data = base.copy() # fresh, unsorted input each time
data.sort_values("x", inplace=True)
copy_only = min(timeit.repeat(lambda: base.copy(), repeat=5, number=5)) / 5
copy_and_sort = min(timeit.repeat(run_once, repeat=5, number=5)) / 5
print(f"copy only: {copy_only * 1000:.1f} ms")
print(f"copy plus sort: {copy_and_sort * 1000:.1f} ms")
print(f"sort alone: {(copy_and_sort - copy_only) * 1000:.1f} ms")Subtracting the cost of the copy gives an estimate of the sort alone. This pattern applies to any operation that mutates its input or caches its result.
Measuring at realistic size
An operation that is fast on 1,000 rows can be slow on 10 million, and the reverse can also be true. Timing on a tiny sample hides costs that grow with size, and it exaggerates fixed overhead. Pandas has a small fixed cost per call, often tens of microseconds. On a tiny frame, that overhead dominates and a vectorized operation can look no faster than a loop.
Time at the size you really use, and, if you can, at two or three sizes. If the time doubles when the rows double, the cost is roughly linear. If it grows faster, you may have a quadratic step, such as repeated concatenation, which a later chapter covers.
Memory is part of performance
Run time is not the only cost. A pipeline that makes many full copies of a large frame may be slow because it is allocating memory. Before you time code that you suspect is memory-bound, check how big the data is.
print(df.memory_usage(deep=True))
print(f"total: {df.memory_usage(deep=True).sum() / 1e6:.1f} MB")memory_usage(deep=True) counts the actual bytes in each column. The deep=True argument matters for object columns, such as strings, because it counts the string objects and not only the pointers to them. Later chapters use this tool to measure the effect of dtype choices.
For peak memory during a function call, Python's standard tracemalloc module tracks allocations made by Python. NumPy reports its array allocations to it, so it sees most pandas data.
import tracemalloc
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
df = pd.DataFrame({"a": rng.random(1_000_000)})
tracemalloc.start()
result = df["a"] * 2
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
print(f"peak during operation: {peak / 1e6:.1f} MB")Tracing slows the code down, so never take timings while tracemalloc is active. Measure time and memory in separate runs.
Common errors
- Timing one run and drawing a conclusion. Repeat the measurement and compare minimums or medians.
- Comparing results from different machines or different load. Compare two versions in the same session, on the same machine, back to back.
- Including data creation or file reading in the timed region when you meant to time only the transformation.
- Timing lazy results. Most pandas operations run immediately, but if you time a generator or an iterator, you may measure nothing. Make sure the work is really executed, for example by consuming the result with
list(...). - Using
time.time()for short intervals. Its resolution can be coarse on some platforms. Useperf_counter. - Measuring the wrong thing. A faster-looking number is meaningless if the output changed. A later chapter shows how to verify that results are identical.
A decision guide
The tools in this chapter cover different situations.
| Situation | Tool |
|---|---|
| Quick check in a script | `perf_counter` around the code, repeated |
| Notebook exploration | `%timeit` or `%%timeit` |
| Reproducible benchmark in a script | `timeit.repeat` with `globals` or a callable |
| Operation that mutates its input | Fresh copy per run, with copy cost subtracted |
| Suspected memory problem | `memory_usage(deep=True)`, `tracemalloc` |
| Finding which step of a pipeline is slow | Profiling, covered in the next chapter |
Workflow summary
Exercise
You time df.sort_values("x", inplace=True) by calling it five times in a row on the same DataFrame, and the later runs look much faster than the first. Name the problem and give two ways to fix the measurement.
Show answer
After the first call the data is already sorted, so later calls do less work and the repeated timings no longer measure sorting unsorted data. Fix it by creating a fresh copy of the unsorted input for every run (for example base.copy() inside the timed function), and either subtract the measured cost of the copy or time only the first call on each fresh copy. Using the minimum of several fresh-input runs gives a stable figure.
Exercise
A colleague reports "my change made the code 3 times faster" after running a script once with time.time() before and after. List three reasons this number could be unreliable and what you would do instead.
Show answer
A single run is noisy because of other processes, CPU clock changes, and one-time warm-up costs. time.time() has coarser resolution and can jump if the clock is adjusted. The two runs may also have happened under different machine load. Instead, wrap the code in a function, do a warm-up call, repeat the timing at least five times with perf_counter or timeit.repeat, compare minimums or medians for both versions in the same session, and confirm the outputs are equal.