Sub topic 18
Benchmarking changes fairly
This chapter shows how to test whether a change made a query faster. The change might be turning on Photon, running OPTIMIZE, adding a broadcast hint, or replacing a UDF. It assumes you can read EXPLAIN output and the Query Profile, and that you know the Delta layout, join and caching topics from earlier chapters. You also need a notebook attached to a cluster or a SQL warehouse where you can run queries repeatedly.
Why one run proves nothing
A single before and after comparison is easy to get wrong. Query times vary for reasons unrelated to your change:
- Another workload shares the cluster or warehouse.
- Cloud storage latency varies from minute to minute.
- Cache state differs between runs.
- Autoscaling adds or removes workers during the test.
If the second run is faster, you can't tell whether your change caused it or the cache did. A fair benchmark changes one thing, controls the other factors, repeats the measurement, and reports a spread instead of one number.
Change one variable at a time
Suppose you want to know whether Photon helps a query, and you also run OPTIMIZE on the table. If the query gets faster, you can't attribute the gain. Keep a written list of the variables and change only one per experiment:
- Compute: runtime engine, Databricks Runtime version, node type, worker count.
- Data: file layout, clustering, statistics.
- Query: hints, rewritten functions, join order.
- Settings: Spark configuration values.
To compare Photon and standard Spark, create two clusters that differ only in runtime_engine. Use the same runtime version, node type and worker count. Run both against the same table at the same table version.
Control caching
Caching is the most common source of misleading results. Three caches matter:
| Cache | Where it lives | Effect on a benchmark |
|---|---|---|
| Disk cache | Local SSDs on the workers | Repeated reads of the same files are much faster. |
| Query result cache | SQL warehouse | An identical query can return the stored result without executing. |
| Spark `cache()` data | Executor memory | Only applies if your code calls it. |
Decide which state you are measuring and say so in your notes. A cold run reflects the first read after a cluster starts. A warm run reflects a steady workload that rereads the same data. Both are valid, but never compare a cold run of one variant with a warm run of another.
On a SQL warehouse, turn off the result cache for the session so the query executes every time:
SET use_cached_result = false;On a cluster, you can turn off the disk cache to measure uncached reads:
spark.conf.set("spark.databricks.io.cache.enabled", "false")If you want warm numbers instead, leave the cache on and discard the first run.
Force the query to run completely
Spark evaluates lazily. A call such as df.limit(10).show() may read only a fraction of the data. To time the whole query without the cost of writing real output, write to the noop format. It executes every stage and discards the rows.
import statistics
import time
QUERY = """
SELECT c.region, SUM(o.amount) AS total
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
WHERE o.order_date >= '2024-01-01'
GROUP BY c.region
"""
def time_query(sql_text, runs=6):
durations = []
for _ in range(runs):
start = time.perf_counter()
spark.sql(sql_text).write.format("noop").mode("overwrite").save()
durations.append(time.perf_counter() - start)
return durations
spark.conf.set("spark.databricks.io.cache.enabled", "false")
durations = time_query(QUERY)
first, rest = durations[0], durations[1:]
print(f"first run: {first:.1f}s")
print(f"median of remaining runs: {statistics.median(rest):.1f}s")
print(f"min: {min(rest):.1f}s max: {max(rest):.1f}s")The script discards no data. It reports the first run separately, because the first run often includes one-time costs such as metadata loading and warm-up. It then summarizes the rest with the median, which a single slow outlier doesn't distort the way it distorts a mean. Run the identical script on each variant.
Use the same data and the same moment
Delta tables change as writers append and compact. If a pipeline writes to the table between your two experiments, you are comparing different data. Two ways to avoid this:
- Pin the table version with time travel, for example
SELECT ... FROM orders VERSION AS OF 120. Both variants read the same snapshot. - Run the experiments against a copy of the table that nothing writes to.
Remember that OPTIMIZE creates a new table version. If you are testing the effect of OPTIMIZE, keep the pre-OPTIMIZE version available so you can run the "before" query against it. The version number comes from DESCRIBE HISTORY orders.
Measure more than elapsed time
Wall-clock time is the headline, but it doesn't explain the result. Record these as well, taken from the Query Profile or the Spark UI:
- Bytes read and files read, which show whether data skipping improved.
- Bytes shuffled and spilled to disk.
- Which operators ran in Photon.
- Total task time, which approximates the compute you consumed.
These numbers let you check that the change worked for the reason you expected. If a clustering change made the query faster but the files read count did not drop, something else caused the speedup. It is probably a cache effect or noise, and the gain may not repeat.
Judge the result against the noise
Look at the spread of your repeated runs. If baseline runs range from 40 to 48 seconds and the variant runs range from 38 to 46 seconds, the two sets overlap and you have no evidence of improvement. A useful rule of thumb is to trust a difference only when the slowest run of the faster variant beats the fastest run of the slower variant, or when the median gap is clearly larger than the spread within each group. If your results are borderline, run more repetitions or use a bigger, more representative workload.
Also check that the test is representative. A query that scans 200 MB may show no Photon benefit, while a production query that scans 2 TB would. Benchmark with realistic data volumes and with the filters and concurrency your real workload uses.
Convert speed into cost
A faster query isn't automatically a cheaper one. Photon-enabled compute is billed at a higher rate than standard compute, so it pays off only when the speedup outweighs the price difference. Compare cost per run:
- Take the run time in hours.
- Multiply by the number of workers plus the driver, and by the hourly rate for each node type, including the rate multiplier for Photon.
- Compare the totals for the baseline and the variant.
If Photon cuts the run from 40 minutes to 15 minutes, the saving usually exceeds the higher rate. If it cuts it from 40 to 36 minutes, the higher rate may erase the gain. Use the actual rates for your account and region, not a rule of thumb. Also count idle time: a shorter job that lets the cluster auto-terminate sooner saves additional cost.
Common mistakes
- Comparing a cold run to a warm run.
- Leaving the result cache on so the "variant" never executed.
- Using
limitorshowso only part of the data was processed. - Testing on a cluster that other jobs were using.
- Changing the table layout and the engine together.
- Reporting the best single run instead of the median.
- Ignoring cost when the speedup is small.
Exercises
Exercise
A teammate reports that adding ZORDER BY (customer_id) cut a query from 90 seconds to 30 seconds. They ran the baseline once right after the cluster started, and the new version once a few minutes later. What is wrong with this comparison, and how would you repeat it fairly?
Show answer
The baseline was a cold run and the new version was probably warm, because the disk cache and metadata were already loaded by the earlier run. Only one run of each was measured, so there is no estimate of noise. To repeat it fairly, pin the table version before and after OPTIMIZE, set the same cache state for both (for example disable the disk cache), run each variant several times with the noop write, discard or separately report the first run, and compare the medians. Also check that files read dropped in the Query Profile, which confirms data skipping caused the gain.
Exercise
Photon reduces a nightly job from 50 minutes to 40 minutes. The Photon cluster costs 1.5 times as much per hour as the standard cluster. Is Photon cheaper for this job?
Show answer
No. Relative cost is (40 / 50) x 1.5 = 1.2, so the Photon run costs about 20 percent more than the standard run, even though it is faster. Photon would pay off here only if the runtime fell below about 33 minutes (50 / 1.5). Check the real rates for your account, and consider whether the 10 minutes saved has value of its own, such as meeting a deadline.