Sub topic 13
Benchmarking on your own data and queries
This chapter assumes you can run the aggregation from the earlier chapters in pandas, Polars, DuckDB, and Spark. It also assumes you know what eager and lazy execution mean. Published benchmarks rarely match your data, your hardware, or your queries. A small benchmark you design yourself gives a more reliable answer.
Decide what you are measuring
Pick the question before you write any timing code. Common questions are:
- How long does the whole job take, from file to result?
- How much peak memory does it use?
- Does it finish at all on the machine you will deploy to?
Use a query and a dataset that resemble production. A filter-and-aggregate over one Parquet file tells you little about a job that joins three tables. Use the real file layout and the real column types too.
Keep the comparison fair
Unfair setups produce misleading winners. Check these points before you trust any number.
- Same input. Read the same Parquet file in every tool. Do not compare pandas reading CSV with DuckDB reading Parquet.
- Same work. Every tool must produce the same result. Compare the outputs, not only the timings.
- Include loading. Eager pandas loads data first. Lazy tools read data during
collect(). Time the full path from file to result in each tool. - Warm and cold runs. The first run may read from disk. Later runs may hit the operating system file cache. Report both, or state which one you measured.
- Repeat. Run several times and report the median and the spread, not the best run.
- Spark startup. Starting a Spark session takes seconds. Measure it separately, and decide whether your real job pays that cost on every run.
A small harness
This script times a function several times and reports the median. It writes a sample Parquet file first, so it runs as shown. Replace the file and the query with your own.
import statistics
import time
import duckdb
import pandas as pd
import polars as pl
pd.DataFrame(
{"region": ["eu", "us", "eu", "apac"] * 250_000, "revenue": range(1_000_000)}
).to_parquet("sales.parquet")
def run_pandas():
df = pd.read_parquet("sales.parquet", columns=["region", "revenue"])
return df.groupby("region")["revenue"].sum()
def run_polars():
return (
pl.scan_parquet("sales.parquet")
.group_by("region")
.agg(pl.col("revenue").sum())
.collect()
)
def run_duckdb():
return duckdb.sql(
"SELECT region, sum(revenue) AS revenue FROM 'sales.parquet' GROUP BY region"
).df()
def bench(fn, repeats=5):
fn() # warm-up run, not recorded
times = []
for _ in range(repeats):
start = time.perf_counter()
fn()
times.append(time.perf_counter() - start)
return statistics.median(times), min(times), max(times)
for name, fn in [("pandas", run_pandas), ("polars", run_polars), ("duckdb", run_duckdb)]:
median, low, high = bench(fn)
print(f"{name:8} median={median:.3f}s min={low:.3f}s max={high:.3f}s")The warm-up call keeps first-run effects out of the recorded times. Remove it if you want to measure cold performance.
Measure at more than one size
A tool that wins on 1 GB may lose on 100 GB. Run the same query on samples at, for example, 1%, 10%, and 100% of your data. Plot time against size. A line that bends upward sharply often marks memory pressure, such as spilling to disk or swapping.
Interpret the results
- A difference of 10–20% is usually noise, and it rarely justifies a migration.
- Weigh runtime against the cost of rewriting code and retraining the team.
- State the hardware, library versions, and data size next to every number you record. Results from one machine do not transfer to another.
Exercise
A colleague times a Polars query by measuring only the line that builds the lazy query with scan_parquet, filter, and group_by. It runs in 2 milliseconds, and they conclude Polars is 50 times faster than pandas. What is wrong, and how do you fix it?
Show answer
The lazy query does no work until collect() is called, so the 2 ms measures only plan construction. Include collect() inside the timed region. The timing should also cover reading the file in every tool, use repeated runs with the median reported, and confirm the outputs match.