Apache DataFusion SQL Query Engine
dev: Add benchmark for compilation profiles (#17754)
Yongting You691dd4727d43
diff --git a/Cargo.toml b/Cargo.tomlindex b9471160b9..b54a75e5d4 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -179,13 +179,56 @@ testcontainers-modules = { version = "0.12" }tokio = { version = "1.47", features = ["macros", "rt", "sync"] }url = "2.5.7"+[workspace.lints.clippy]+# Detects large stack-allocated futures that may cause stack overflow crashes (see threshold in clippy.toml)+large_futures = "warn"+used_underscore_binding = "warn"+or_fun_call = "warn"+unnecessary_lazy_evaluations = "warn"+uninlined_format_args = "warn"+inefficient_to_string = "warn"++[workspace.lints.rust]+unexpected_cfgs = { level = "warn", check-cfg = [+ 'cfg(datafusion_coop, values("tokio", "tokio_fallback", "per_stream"))',+ "cfg(tarpaulin)",+ "cfg(tarpaulin_include)",+] }+unused_qualifications = "deny"++# --------------------+# Compilation Profiles+# --------------------+# A Cargo profile is a preset for the compiler/linker knobs that trade off:+# - Build time: how quickly code compiles and links+# - Runtime performance: how fast the resulting binaries execute+# - Binary size: how large the executables end up+# - Debuggability: how much debug information is preserved for debugging and profiling+#+# Profiles available:+# - dev: default debug build; fastest to compile, slowest to run, full debug info+# for everyday development.+# Run: cargo run+# - release: optimized build; slowest to compile, fastest to run, smallest+# binaries for public releases.+# Run: cargo run --release+# - release-nonlto: skips LTO, so it builds quicker while staying close to+# release performance. It is useful when developing performance optimizations.+# Run: cargo run --profile release-nonlto+# - profiling: inherits release optimizations but retains debug info to support+# profiling tools and flamegraphs.+# Run: cargo run --profile profiling+# - ci: derived from `dev` but disables incremental builds and strips dependency+# symbols to keep CI artifacts small and reproducible.+# Run: cargo run --profile ci+#+# If you want to optimize compilation, the `compile_profile` benchmark can be useful.+# See `benchmarks/README.md` for more details.[profile.release]codegen-units = 1lto = truestrip = true # Eliminate debug information to minimize binary size-# the release profile takes a long time to build so we can use this profile during development to save time-# cargo build --profile release-nonlto[profile.release-nonlto]codegen-units = 16debug-assertions = false@@ -202,33 +245,16 @@ debug = falseinherits = "dev"incremental = false-# ci turns off debug info, etc. for dependencies to allow for smaller binaries making caching more effective+# This rule applies to every package except workspace members (dependencies+# such as `arrow` and `tokio`). It disables debug info and related features on+# dependencies so their binaries stay smaller, improving cache reuse.[profile.ci.package."*"]debug = falsedebug-assertions = falsestrip = "debuginfo"incremental = false-# release inherited profile keeping debug information and symbols-# for mem/cpu profiling[profile.profiling]inherits = "release"debug = truestrip = false--[workspace.lints.clippy]-# Detects large stack-allocated futures that may cause stack overflow crashes (see threshold in clippy.toml)-large_futures = "warn"-used_underscore_binding = "warn"-or_fun_call = "warn"-unnecessary_lazy_evaluations = "warn"-uninlined_format_args = "warn"-inefficient_to_string = "warn"--[workspace.lints.rust]-unexpected_cfgs = { level = "warn", check-cfg = [- 'cfg(datafusion_coop, values("tokio", "tokio_fallback", "per_stream"))',- "cfg(tarpaulin)",- "cfg(tarpaulin_include)",-] }-unused_qualifications = "deny"diff --git a/benchmarks/README.md b/benchmarks/README.mdindex 872500ef84..0399f8a7ff 100644--- a/benchmarks/README.md+++ b/benchmarks/README.md@@ -87,6 +87,39 @@ To run for specific query, for example Q21./bench.sh run tpch10 21```+## Compile profile benchmark++Generate the data required for the compile profile helper (TPC-H SF=1):++```shell+./bench.sh data compile_profile+```++Run the benchmark across all default Cargo profiles (`dev`, `release`, `ci`, `release-nonlto`):++```shell+./bench.sh run compile_profile+```++Limit the run to a single profile:++```shell+./bench.sh run compile_profile dev+```++Or specify a subset of profiles:++```shell+./bench.sh run compile_profile dev release+```++You can also invoke the helper directly if you need to customise arguments further:++```shell+./benchmarks/compile_profile.py --profiles dev release --data /path/to/tpch_sf1+```++## Benchmark with modified configurations### Select join algorithmdiff --git a/benchmarks/bench.sh b/benchmarks/bench.shindex b99ab01005..56af6b458c 100755--- a/benchmarks/bench.sh+++ b/benchmarks/bench.sh@@ -125,6 +125,7 @@ imdb: Join Order Benchmark (JOB) using the IMDB dataset conver# Micro-Benchmarks (specific operators and features)cancellation: How long cancelling a query takesnlj: Benchmark for simple nested loop joins, testing various join scenarios+compile_profile: Compile and execute TPC-H across selected Cargo profiles, reporting timing and binary size━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━Supported Configuration (Environment Variables)@@ -304,6 +305,9 @@ main() {# nlj uses range() function, no data generation neededecho "NLJ benchmark does not require data generation";;+ compile_profile)+ data_tpch "1"+ ;;*)echo "Error: unknown benchmark '$BENCHMARK' for data generation"usage@@ -313,20 +317,32 @@ main() {run)# Parse positional parametersBENCHMARK=${ARG2:-"${BENCHMARK}"}+ EXTRA_ARGS=("${POSITIONAL_ARGS[@]:2}")+ PROFILE_ARGS=()+ QUERY=""+ QUERY_ARG=""+ if [ "$BENCHMARK" = "compile_profile" ]; then+ PROFILE_ARGS=("${EXTRA_ARGS[@]}")+ else+ QUERY=${EXTRA_ARGS[0]}+ if [ -n "$QUERY" ]; then+ QUERY_ARG="--query ${QUERY}"+ fi+ fiBRANCH_NAME=$(cd "${DATAFUSION_DIR}" && git rev-parse --abbrev-ref HEAD)BRANCH_NAME=${BRANCH_NAME//\//_} # mind blowing syntax to replace / with _RESULTS_NAME=${RESULTS_NAME:-"${BRANCH_NAME}"}RESULTS_DIR=${RESULTS_DIR:-"$SCRIPT_DIR/results/$RESULTS_NAME"}- # Optional query filter to run specific query- QUERY=${ARG3}- QUERY_ARG=$([ -n "$QUERY" ] && echo "--query ${QUERY}" || echo "")-echo "***************************"echo "DataFusion Benchmark Script"echo "COMMAND: ${COMMAND}"echo "BENCHMARK: ${BENCHMARK}"- echo "QUERY: ${QUERY:-All}"+ if [ "$BENCHMARK" = "compile_profile" ]; then+ echo "PROFILES: ${PROFILE_ARGS[*]:-All}"+ else+ echo "QUERY: ${QUERY:-All}"+ fiecho "DATAFUSION_DIR: ${DATAFUSION_DIR}"echo "BRANCH_NAME: ${BRANCH_NAME}"echo "DATA_DIR: ${DATA_DIR}"@@ -468,6 +484,9 @@ main() {nlj)run_nlj;;+ compile_profile)+ run_compile_profile "${PROFILE_ARGS[@]}"+ ;;*)echo "Error: unknown benchmark '$BENCHMARK' for run"usage@@ -593,6 +612,20 @@ run_tpch_mem() {debug_run $CARGO_COMMAND --bin tpch -- benchmark datafusion --iterations 5 --path "${TPCH_DIR}" --prefer_hash_join "${PREFER_HASH_JOIN}" -m --format parquet -o "${RESULTS_FILE}" ${QUERY_ARG}}+# Runs the compile profile benchmark helper+run_compile_profile() {+ local profiles=("$@")+ local runner="${SCRIPT_DIR}/compile_profile.py"+ local data_path="${DATA_DIR}/tpch_sf1"++ echo "Running compile profile benchmark..."+ local cmd=(python3 "${runner}" --data "${data_path}")+ if [ ${#profiles[@]} -gt 0 ]; then+ cmd+=(--profiles "${profiles[@]}")+ fi+ debug_run "${cmd[@]}"+}+# Runs the cancellation benchmarkrun_cancellation() {RESULTS_FILE="${RESULTS_DIR}/cancellation.json"diff --git a/benchmarks/compile_profile.py b/benchmarks/compile_profile.pynew file mode 100644index 0000000000..ae51de9493--- /dev/null+++ b/benchmarks/compile_profile.py@@ -0,0 +1,180 @@+#!/usr/bin/env python3++# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.++"""Compile profile benchmark runner for DataFusion.++Builds the `tpch` benchmark binary with several Cargo profiles (e.g. `--release` or `--profile ci`), runs the full TPC-H suite against the Parquet data under `benchmarks/data/tpch_sf1`, and reports compile time, execution time, and resulting+binary size.++See `benchmarks/README.md` for usages.+"""++from __future__ import annotations++import argparse+import os+import subprocess+import sys+import time+from pathlib import Path+from typing import Iterable, NamedTuple++REPO_ROOT = Path(__file__).resolve().parents[1]+DEFAULT_DATA_DIR = REPO_ROOT / "benchmarks" / "data" / "tpch_sf1"+DEFAULT_ITERATIONS = 1+DEFAULT_FORMAT = "parquet"+DEFAULT_PARTITIONS: int | None = None+TPCH_BINARY = "tpch.exe" if os.name == "nt" else "tpch"+PROFILE_TARGET_DIR = {+ "dev": "debug",+ "release": "release",+ "ci": "ci",+ "release-nonlto": "release-nonlto",+}+++class ProfileResult(NamedTuple):+ profile: str+ compile_seconds: float+ run_seconds: float+ binary_bytes: int+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "--profiles",+ nargs="+",+ default=list(PROFILE_TARGET_DIR.keys()),+ help="Cargo profiles to test (default: dev release ci release-nonlto)",+ )+ parser.add_argument(+ "--data",+ type=Path,+ default=DEFAULT_DATA_DIR,+ help="Path to TPCH dataset (default: benchmarks/data/tpch_sf1)",+ )+ return parser.parse_args()+++def timed_run(command: Iterable[str]) -> float:+ start = time.perf_counter()+ try:+ subprocess.run(command, cwd=REPO_ROOT, check=True)+ except subprocess.CalledProcessError as exc:+ raise RuntimeError(f"command failed: {' '.join(command)}") from exc+ return time.perf_counter() - start+++def cargo_build(profile: str) -> float:+ if profile == "dev":+ command = ["cargo", "build", "--bin", "tpch"]+ else:+ command = ["cargo", "build", "--profile", profile, "--bin", "tpch"]+ return timed_run(command)+++def cargo_clean(profile: str) -> None:+ command = ["cargo", "clean", "--profile", profile]+ try:+ subprocess.run(command, cwd=REPO_ROOT, check=True)+ except subprocess.CalledProcessError as exc:+ raise RuntimeError(f"failed to clean cargo artifacts for profile '{profile}'") from exc+++def run_benchmark(profile: str, data_path: Path) -> float:+ binary_dir = PROFILE_TARGET_DIR.get(profile)+ if not binary_dir:+ raise ValueError(f"unknown profile '{profile}'")+ binary_path = REPO_ROOT / "target" / binary_dir / TPCH_BINARY+ if not binary_path.exists():+ raise FileNotFoundError(f"compiled binary not found at {binary_path}")++ command = [+ str(binary_path),+ "benchmark",+ "datafusion",+ "--iterations",+ str(DEFAULT_ITERATIONS),+ "--path",+ str(data_path),+ "--format",+ DEFAULT_FORMAT,+ ]+ if DEFAULT_PARTITIONS is not None:+ command.extend(["--partitions", str(DEFAULT_PARTITIONS)])+ env = os.environ.copy()+ env.setdefault("RUST_LOG", "warn")++ start = time.perf_counter()+ try:+ subprocess.run(command, cwd=REPO_ROOT, env=env, check=True)+ except subprocess.CalledProcessError as exc:+ raise RuntimeError(f"benchmark failed for profile '{profile}'") from exc+ return time.perf_counter() - start+++def binary_size(profile: str) -> int:+ binary_dir = PROFILE_TARGET_DIR[profile]+ binary_path = REPO_ROOT / "target" / binary_dir / TPCH_BINARY+ return binary_path.stat().st_size+++def human_time(seconds: float) -> str:+ return f"{seconds:6.2f}s"+++def human_size(size: int) -> str:+ value = float(size)+ for unit in ("B", "KB", "MB", "GB", "TB"):+ if value < 1024 or unit == "TB":+ return f"{value:6.1f}{unit}"+ value /= 1024+ return f"{value:6.1f}TB"+++def main() -> None:+ args = parse_args()+ data_path = args.data.resolve()+ if not data_path.exists():+ print(f"Data directory not found: {data_path}", file=sys.stderr)+ sys.exit(1)++ results: list[ProfileResult] = []+ for profile in args.profiles:+ print(f"\n=== Profile: {profile} ===")+ print("Cleaning previous build artifacts...")+ cargo_clean(profile)+ compile_seconds = cargo_build(profile)+ run_seconds = run_benchmark(profile, data_path)+ size_bytes = binary_size(profile)+ results.append(ProfileResult(profile, compile_seconds, run_seconds, size_bytes))++ print("\nSummary")+ header = f"{'Profile':<15}{'Compile':>12}{'Run':>12}{'Size':>12}"+ print(header)+ print("-" * len(header))+ for result in results:+ print(+ f"{result.profile:<15}{human_time(result.compile_seconds):>12}"+ f"{human_time(result.run_seconds):>12}{human_size(result.binary_bytes):>12}"+ )++if __name__ == "__main__":+ main()