Sub topic 13
Benchmarking on your own data and queries
This chapter shows how to measure the four tools on your own workload, so you can trust the result. It assumes you have read the earlier chapters on execution models, memory limits, and distribution costs. It also assumes you can run Python scripts from a terminal and are comfortable reading the same aggregation written in pandas, Polars, DuckDB, and Spark.
Why published numbers rarely transfer
Published benchmarks answer someone else's question. They fix a dataset, a machine, a query set, and a file format. Your workload differs in at least one of these, and each difference can change the ranking.
- Data shape. Many narrow columns, a few wide string columns, and high-cardinality group keys stress engines differently.
- Hardware. Core count, memory size, and disk speed decide how much a parallel or out-of-core engine can help.
- Query mix. A benchmark of one large group-by says little about a pipeline of many small joins and string operations.
- Tuning. A vendor may tune its own tool and run others with defaults.
Use published numbers to form a hypothesis, such as "a lazy engine should help here", and then test it on your own data.
Define the question first
A benchmark with no stated question produces a table of numbers and no decision. Write down four things before you run anything:
- The workload. Name the real queries, such as "daily revenue by region from last quarter's Parquet files".
- The metric that matters. This might be wall-clock time, peak memory, cost per run, or developer time. A job that runs nightly cares about cost and reliability. An analyst in a notebook cares about latency.
- The scale. Test today's data size and the size you expect in a year. A tool that wins at 2 GB may lose at 200 GB, and the reverse can also happen.
- The threshold. Decide what counts as good enough. If every candidate finishes a nightly job in two minutes, speed is not the deciding factor and you should choose on other criteria.
The benchmarking process
Prepare representative data
Use real data, or a sample that keeps its properties. A random sample of rows usually keeps the distribution of values, but it changes the number of distinct group keys and the join match rates. Check these on the sample.
Keep the file format the same for every tool. Parquet is the fair default, because all four tools read it natively. Do not time CSV against Parquet and call it a tool comparison. Do not include a one-time format conversion in one tool's timing unless production would pay that cost on every run.
To test scale, make 1x, 10x, and 100x versions of the data, within the limits of your disk. Plot or tabulate time against size. The shape of the curve matters more than any single point. A curve that rises steeply where memory runs out means swapping or spilling to disk.
Verify equivalence before timing
A fast query that returns the wrong answer is worthless. The tools differ in null handling, integer overflow, string sorting, and the output types of aggregations. For example, DuckDB may widen the sum of an integer column, and a group key may arrive as object in one tool and as a string type in another. Compare results with a tolerance and without strict dtype checks, and investigate any real difference.
A small harness
The script below benchmarks pandas, Polars, and DuckDB on the filter-and-aggregate task from earlier chapters. Each run executes in its own process, so peak memory is not polluted by another tool. Libraries are imported inside each function for the same reason. It uses the Unix-only resource module, so run it on Linux or macOS. It also needs pyarrow installed, because Polars converts to pandas through Arrow.
import json
import resource
import statistics
import sys
import time
PATH = "sales.parquet"
def run_pandas():
import pandas as pd
df = pd.read_parquet(PATH, columns=["region", "revenue"])
df = df[df["revenue"] > 0]
return df.groupby("region", as_index=False)["revenue"].sum()
def run_polars():
import polars as pl
return (
pl.scan_parquet(PATH)
.filter(pl.col("revenue") > 0)
.group_by("region")
.agg(pl.col("revenue").sum())
.collect()
.to_pandas()
)
def run_duckdb():
import duckdb
return duckdb.sql(
"SELECT region, sum(revenue) AS revenue "
"FROM 'sales.parquet' WHERE revenue > 0 GROUP BY region"
).df()
RUNNERS = {"pandas": run_pandas, "polars": run_polars, "duckdb": run_duckdb}
def normalize(df):
out = df.copy()
out["region"] = out["region"].astype(str)
return out.sort_values("region").reset_index(drop=True)
def peak_rss_mb():
peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
# ru_maxrss is in bytes on macOS and in kilobytes on Linux
return peak / (1024 * 1024) if sys.platform == "darwin" else peak / 1024
def check():
from pandas.testing import assert_frame_equal
expected = normalize(RUNNERS["pandas"]())
for name, runner in RUNNERS.items():
assert_frame_equal(
expected, normalize(runner()), check_dtype=False, check_exact=False
)
print(f"{name}: results match pandas")
def bench(name, repeats):
times = []
for _ in range(repeats):
start = time.perf_counter()
RUNNERS[name]()
times.append(time.perf_counter() - start)
print(
json.dumps(
{
"tool": name,
"first_s": round(times[0], 3),
"median_s": round(statistics.median(times[1:] or times), 3),
"peak_rss_mb": round(peak_rss_mb()),
}
)
)
if __name__ == "__main__":
if sys.argv[1] == "check":
check()
else:
bench(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 5)Run python bench.py check first. Then run python bench.py pandas 5, python bench.py polars 5, and python bench.py duckdb 5 as separate commands.
Measurement rules
- Force execution. A lazy tool does no work until an action runs. Calling
scan_parquet(...).filter(...)withoutcollect()times only plan construction. In Spark,show()computes only a few rows, which can hide most of the cost. Usecollect(), or write to thenoopformat withdf.write.format("noop").mode("overwrite").save()to run the full plan without storing output. - Report the first run and the median of the rest. The first run pays for cold operating-system file caches and library initialization. The later runs show steady-state speed. Show both, because production may behave like either one.
- Repeat enough times to see the spread. Five runs is a minimum. If the slowest run is twice the fastest, the machine is noisy, so find out why before comparing tools.
- Count the whole job. Include reading the data and producing the output you need. Excluding load time favors pandas, which spends much of its time loading. Including a conversion to pandas at the end penalizes DuckDB and Polars for a step you may not need.
- Measure memory per process. Peak resident memory shows whether a job fits on the target machine. Compare it with the size of the data on disk and in memory, using the estimates from the memory chapter.
- Pin the environment. Record library versions, core count, and RAM. Use the same machine for all tools, and close other heavy programs.
Measuring Spark fairly
Spark needs separate treatment because its costs come in two parts. Session startup and JVM warm-up take seconds and are paid once per application. Per-query work includes scheduling, shuffles, and task overhead. Report startup separately from query time. Then ask which one production will pay. A long-lived cluster pays startup once. A job that launches a fresh cluster each night pays it every time.
Run Spark on the hardware you would use in production. Spark on a laptop in local mode says little about a cluster, because shuffles then cross a network instead of staying in memory. Include cluster cost in the comparison: node-hours multiplied by the price, not only elapsed seconds.
Common benchmarking mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Timing only plan construction in a lazy tool | Looks absurdly fast | Call `collect()` or a Spark action |
| Comparing different file formats | Measures the format, not the tool | Use the same Parquet files for all tools |
| One run only | Cold-cache and noise dominate | Repeat and report first and median |
| Not checking results | A fast wrong answer wins | Compare outputs before timing |
| Running all tools in one process | Memory numbers are mixed | One process per tool and run |
| Testing only small data | Misses memory limits and shuffle costs | Test several scales |
| Tuning one tool and not the others | Biased ranking | Give each tool the same effort |
| Ignoring developer time | Fastest tool may be costly to adopt | Record lines of code and time to write |
Reading the results
Put timings, peak memory, and the effort to write each version in one table. Then compare the winners with your threshold from the start. If two tools meet it, choose by the other criteria in the decision chapter: team skills, deployment, and ecosystem. If no tool meets it, check whether the cause is the engine, the file layout (for example many small files or no partitioning), or the query. A change to the Parquet layout often helps every engine more than switching tools does.
Exercise
A teammate benchmarked Polars and pandas on a 500 MB Parquet file. Their Polars code was pl.scan_parquet("data.parquet").filter(pl.col("x") > 0).group_by("k").agg(pl.col("v").sum()) and it took 0.002 seconds. The pandas version took 3 seconds. Name two problems with this comparison and how to fix each.
Show answer
First, the Polars code never calls collect(), so it builds a lazy plan and does no work. Add .collect() so the timing includes execution. Second, the result of the two versions has not been checked for equality, and each was run once. Compare the outputs after normalizing sort order and types, then repeat the runs and report the first run and the median of the rest. Also confirm that both versions read only the needed columns and include the same loading and output steps.
Exercise
Why does the harness in this chapter run each tool in its own process instead of looping over all three tools in one script?
Show answer
Peak resident memory is a per-process high-water mark. If all tools ran in one process, the number would reflect the largest earlier tool plus loaded libraries, not the tool being measured. Separate processes also avoid shared caches and imports from one tool affecting another.