Sub topic 3
Measuring the speedup and verifying results
A vectorised rewrite is only useful if it is faster and still gives the same answer. This chapter shows how to time both versions fairly and how to check that their results match. It also covers the ways a benchmark can mislead you.
This chapter assumes you can write Python functions and loops, build a pandas DataFrame and Series, and read basic NumPy-style column arithmetic. You should also have seen the loop-versus-column example from the earlier chapters.
Why measure at all
You may already believe the column version is faster. Measure anyway, for three reasons:
- The speedup depends on data size, and for tiny frames it can be close to zero.
- A rewrite can change results in subtle ways, such as dtype, index, or floating-point rounding.
- Intuition about where the time goes is often wrong. The slow part may be a different line from the one you rewrote.
The workflow has two halves. First check that the new code is correct, then time it. Timing code that gives a wrong answer is meaningless.
Step 1: wrap each version in a function
To time code, put each version in a function that takes the DataFrame and returns the result. This keeps the comparison honest, because both versions get the same input and return the same kind of object.
import pandas as pd
def with_loop(frame):
out = []
for _, row in frame.iterrows():
out.append(row["price"] * row["qty"])
return pd.Series(out, index=frame.index)
def with_columns(frame):
return frame["price"] * frame["qty"]Notice that with_loop passes index=frame.index to the new Series. Without it, the loop result would get a fresh 0, 1, 2, ... index. If the frame has a different index, the two results would not line up. The next section shows why that matters.
Step 2: check equivalence first
The simplest check is Series.equals. It returns True only if the shape, the values, and the dtype all match. It also treats NaN in the same position as equal, which == does not.
import timeit
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0, 15.0], "qty": [3, 1, 4]})
def with_loop(frame):
out = []
for _, row in frame.iterrows():
out.append(row["price"] * row["qty"])
return pd.Series(out, index=frame.index)
def with_columns(frame):
return frame["price"] * frame["qty"]
assert with_loop(df).equals(with_columns(df))
print(timeit.timeit(lambda: with_loop(df), number=100))
print(timeit.timeit(lambda: with_columns(df), number=100))The assert stops the script if the results differ, so the timing lines never run on a wrong rewrite. The two printed numbers are the total seconds for 100 calls each. Your numbers will differ from anyone else's, because they depend on your machine. What matters is the ratio between them.
What `equals` is strict about
equals is strict, and that is usually what you want. These cases make it return False:
| Difference | Example | Why it matters |
|---|---|---|
| Dtype | `int64` versus `float64` | Downstream code may behave differently, and memory use differs. |
| Index | Labels differ or are in a different order | Later assignments align on labels and can silently produce `NaN`. |
| Length | One result is missing rows | Usually a filtering bug. |
| Float rounding | Values differ in the last digits | Often harmless, but `equals` cannot tell harmless from harmful. |
Here is the dtype case:
import pandas as pd
ints = pd.Series([1, 2])
floats = pd.Series([1.0, 2.0])
print(ints.equals(floats))This prints False, even though the numbers are equal in value.
Step 3: use a tolerant comparison for floats
Loops and vectorised code can add numbers in a different order. Floating-point addition is not exactly associative, so a loop that accumulates a sum and Series.sum() can differ in the last digits. A multiplication of two columns is usually identical in both versions, but sums, means, and chained operations often are not.
For those cases use pandas.testing.assert_series_equal. It raises an AssertionError with a clear message when the results differ. By default it allows tiny floating-point differences, with rtol=1e-5 as the relative tolerance, and it checks dtype and index.
import pandas as pd
from pandas.testing import assert_series_equal
expected = pd.Series([1, 2])
actual = pd.Series([1.0, 2.0])
# Fails on dtype by default:
try:
assert_series_equal(expected, actual)
except AssertionError as err:
print("dtype mismatch caught")
# Passes once the dtype check is relaxed on purpose:
assert_series_equal(expected, actual, check_dtype=False)
print("values match")Prefer assert_series_equal over equals for real work. When it fails, the message tells you which values or attributes differ. equals only returns False.
For whole DataFrames, the matching function is pandas.testing.assert_frame_equal.
Step 4: time with repeats
A single timing is noisy. Other programs use the CPU, caches warm up, and Python's memory allocator behaves differently on the first call. timeit.repeat runs the whole measurement several times. Taking the minimum of the repeats gives the run least disturbed by other activity, which is the standard way to compare two pieces of code.
import timeit
import numpy as np
import pandas as pd
def with_loop(frame):
out = []
for _, row in frame.iterrows():
out.append(row["price"] * row["qty"])
return pd.Series(out, index=frame.index)
def with_columns(frame):
return frame["price"] * frame["qty"]
rng = np.random.default_rng(0)
for n in [10, 1_000, 50_000]:
frame = pd.DataFrame({
"price": rng.uniform(1, 100, n),
"qty": rng.integers(1, 10, n),
})
assert with_loop(frame).equals(with_columns(frame))
loop_s = min(timeit.repeat(lambda: with_loop(frame), number=1, repeat=3))
vec_s = min(timeit.repeat(lambda: with_columns(frame), number=1, repeat=3))
print(f"n={n:>6} loop={loop_s:.5f}s vectorised={vec_s:.5f}s "
f"speedup={loop_s / vec_s:.0f}x")The loop for 50,000 rows takes a few seconds per call, so the script may run for around ten seconds. Each size gets its own equivalence check before it is timed.
Reading the output
Run the script and look at how the speedup changes with n. You will typically see a pattern like this:
- At 10 rows, the speedup is modest. Both versions are dominated by fixed overhead, such as creating a Series and calling pandas methods.
- At 1,000 rows, the loop is clearly slower.
- At 50,000 rows, the gap is large, often by two orders of magnitude.
The loop time grows roughly in proportion to the number of rows, because each row costs a fixed amount of Python work. The vectorised time grows much more slowly, because the per-row work happens in compiled code. That is why the speedup ratio itself grows with data size.
This is also why a benchmark on a three-row frame, like the one in Step 2, tells you almost nothing about production behaviour. Always time at a size close to your real data.
Choosing `number` and `repeat`
timeit.timeit(f, number=100) calls f 100 times and returns the total. timeit.repeat(f, number=1, repeat=3) returns a list of three totals, each for one call.
- For slow code like a row loop, use a small
numbersuch as 1, so the benchmark finishes. - For fast code, use a larger
numberso each measurement lasts at least a few milliseconds. Otherwise the timer resolution adds noise. - Divide a total by
numberif you want a per-call time. - Report the minimum of the repeats for comparing two implementations. Report the spread, from the minimum to the maximum, if you want to show how noisy the machine is.
In a Jupyter notebook, the %timeit magic picks number and repeat for you. In a plain script, use the timeit module as shown above.
Common ways a benchmark misleads
Timing the setup, not the work
Build the DataFrame outside the timed function. If with_loop creates its own data, you are measuring data creation as well. Pass the frame in as an argument, as the examples do.
Letting one version modify the data
If a function assigns a new column to frame, the next run sees a frame that already has it. Return a Series, as above, or work on frame.copy() inside the function and include that cost in both versions.
Comparing different amounts of work
A common error is for the loop version to return a plain list while the vectorised version returns a Series. A list is cheaper to build. Return the same type from both, and check equality on that type.
Caching and first-call effects
The first call can be slower, for example because of imports or lazy initialisation. Taking the minimum over repeats removes most of this. For a stricter comparison, call each function once before you start timing.
Trusting speedups on a different machine or pandas version
Absolute times depend on the CPU, the pandas version, and the NumPy version. Compare the two implementations on the same machine in the same session. Record the pandas version with pd.__version__ if you share results.
Profile before you rewrite
Measuring also tells you what to rewrite. If a function takes ten seconds, time its parts separately. Often one loop accounts for nearly all of it, and rewriting only that loop captures the whole gain. Simple tools are enough:
- Time the whole function once.
- Wrap each suspect section in its own
timeitcall, or usetime.perf_counter()before and after it. - Rewrite the slowest section first, then check equivalence and time again.
For deeper analysis, Python's built-in cProfile reports time per function call. A row loop appears there as thousands of calls into pandas indexing code, which is a clear signal.
Putting it together: a reusable helper
You will repeat the check-then-time pattern for every rewrite in this tutorial, so it helps to keep a small function for it.
import timeit
import pandas as pd
from pandas.testing import assert_series_equal
def compare(slow, fast, frame, repeat=3):
"""Check that two Series-returning functions agree, then time them."""
assert_series_equal(slow(frame), fast(frame))
slow_s = min(timeit.repeat(lambda: slow(frame), number=1, repeat=repeat))
fast_s = min(timeit.repeat(lambda: fast(frame), number=1, repeat=repeat))
print(f"slow={slow_s:.5f}s fast={fast_s:.5f}s speedup={slow_s / fast_s:.0f}x")
df = pd.DataFrame({"price": [10.0, 20.0, 15.0], "qty": [3, 1, 4]})
def with_loop(frame):
out = []
for _, row in frame.iterrows():
out.append(row["price"] * row["qty"])
return pd.Series(out, index=frame.index)
def with_columns(frame):
return frame["price"] * frame["qty"]
compare(with_loop, with_columns, df)If the two functions disagree, assert_series_equal raises before any timing happens. The later chapters reuse this pattern whenever they rewrite a loop.
Summary of the habits
- Put each version in a function with the same input and the same output type.
- Check equivalence first, with
assert_series_equalfor anything involving floats. - Time with
timeit.repeatand compare minimums. - Time at several sizes, including one close to your real data.
- Keep setup and data creation out of the timed code.
Exercise
You rewrite a loop that computes a running total into a vectorised version. slow(frame).equals(fast(frame)) returns False, but printing both results shows the same numbers. Name two likely causes and the check that would reveal each.
Show answer
Likely causes are a dtype difference (for example int64 against float64) and an index difference (for example a default 0..n-1 index against the original frame's labels). Calling assert_series_equal instead of equals reports which attribute differs. You can also compare slow(frame).dtype with fast(frame).dtype and slow(frame).index with fast(frame).index. A third cause is last-digit float rounding from a different order of addition, which assert_series_equal tolerates by default.
Exercise
A colleague times a vectorised rewrite on a 5-row sample, sees only a 2x speedup, and concludes the rewrite is not worth keeping. What is wrong with this conclusion, and what would you do instead?
Show answer
At 5 rows, fixed overhead dominates both versions, so the speedup is not representative. The loop cost grows with the number of rows, while the vectorised cost grows much more slowly. Time both versions at a size close to the real data, such as tens of thousands of rows, with timeit.repeat and the minimum of the repeats. Check equivalence with assert_series_equal before timing.