--- name: benchmark description: Benchmarking fundamentals and dispatcher — routes to language-specific skills (Go, Rust, Zig, Java, Lua). Use when measuring performance, comparing implementations, or avoiding common pitfalls: warm-up, compiler optimization, statistical noise. license: MIT --- ## What I Do Guide benchmarking across languages and help avoid common pitfalls. ## Routing This skill routes to language-specific benchmark skills: - **Go** → `/benchmark-go` (`testing.B`, `benchstat`) - **Rust** → `/benchmark-rust` (Criterion.rs) - **Zig** → `/benchmark-zig` (zBench) - **Java** → `/benchmark-java` (JMH) - **Lua** → `/benchmark-lua` (os.clock, LuaJIT profiler) Use the appropriate language-specific skill for detailed guidance. --- ## Universal Benchmarking Principles ### The Golden Rule **Always measure what you actually want to optimize.** Sounds obvious, but it's the #1 source of bad benchmarks. --- ## Common Pitfalls ### 1. Compiler Optimizing Away Your Code The compiler is smarter than you. If your benchmark doesn't use the result, the compiler may eliminate the entire computation. ```rust // BAD: Compiler may eliminate this fn bench_addition(b: &mut Bencher) { b.iter(|| 2 + 2); } // GOOD: Force the compiler to keep the result fn bench_addition(b: &mut Bencher) { b.iter(|| black_box(2 + 2)); } ``` **Every language has a solution:** - Rust: `std::hint::black_box()` or Criterion's `BatchSize` - Go: Don't use a solution—Go's compiler is less aggressive - C/C++: `asm volatile("" : : "r"(x) : "memory")` or `do_not_optimize` - Java: JMH's `Blackhole.consume()` ### 2. Insufficient Warm-up The first run is always slower: CPU caches are cold, branch predictors haven't learned, JIT compilers haven't compiled. ```rust // GOOD: Criterion handles warm-up automatically let mut group = c.benchmark_group("comparison"); group.bench_function("approach_a", |b| b.iter(|| approach_a())); group.bench_function("approach_b", |b| b.iter(|| approach_b())); group.finish(); ``` **Warm-up is critical for:** - JIT-compiled languages (Java, JavaScript, LuaJIT) - Any benchmark lasting < 100ms - Benchmarks with cold caches ### 3. Statistical Noise A single measurement tells you nothing. You need statistical analysis. ```rust // BAD: Single timing let start = Instant::now(); do_work(); let elapsed = start.elapsed(); // Meaningless without context // GOOD: Statistical analysis let mut timings = Vec::new(); for _ in 0..100 { let start = Instant::now(); do_work(); timings.push(start.elapsed()); } let mean = timings.iter().sum::() / timings.len() as u32; let stddev = calculate_stddev(&timings); ``` **Tools that handle this:** - Criterion.rs: Automatic statistical analysis, outlier detection - JMH: Statistical output, confidence intervals - benchstat (Go): Compare multiple runs with statistical significance ### 4. Measuring the Wrong Thing ```rust // BAD: Includes allocation overhead in what you're trying to measure fn bench_parsing(b: &mut Bencher) { b.iter(|| { let input = generate_large_string(); // Allocation here! parse(&input) }); } // GOOD: Separate setup from measurement fn bench_parsing(b: &mut Bencher) { let input = generate_large_string(); // Setup outside iter b.iter(|| parse(&input)); } ``` ### 5. I/O in Microbenchmarks I/O is orders of magnitude slower and more variable than computation. It dominates your timing. ```rust // BAD: File I/O in microbenchmark fn bench_parse_file(b: &mut Bencher) { b.iter(|| std::fs::read_to_string("data.json").unwrap()); } // GOOD: Load once, measure parsing only fn bench_parse_file(b: &mut Bencher) { let data = std::fs::read_to_string("data.json").unwrap(); b.iter(|| parse_json(&data)); } ``` ### 6. Wall Clock vs CPU Time Wall-clock time includes other processes. CPU time is what your code actually used. - **Wall-clock**: `Instant::now()`, `time.time()` - **CPU time**: `process_time()`, `clock_gettime(CLOCK_PROCESS_CPUTIME_ID)` For microbenchmarks, CPU time is usually what you want. --- ## Benchmarking Checklist Before trusting a benchmark: - [ ] Result is actually used (not optimized away) - [ ] Warm-up runs completed - [ ] Multiple iterations with statistical analysis - [ ] Setup/teardown separated from measured code - [ ] No I/O in microbenchmarks - [ ] Consistent results across multiple runs - [ ] Understood the difference between wall-clock and CPU time --- ## When to Benchmark - **Before optimization**: Establish a baseline - **During optimization**: Verify improvements - **After optimization**: Confirm no regressions - **Comparing approaches**: A vs B with statistical significance --- ## Comparison with Statistical Significance ```bash # Go: Run multiple times, compare with benchstat go test -bench=. -count=10 > old.txt # ... make changes ... go test -bench=. -count=10 > new.txt benchstat old.txt new.txt ``` ```rust // Rust: Criterion handles this automatically let mut group = c.benchmark_group("comparison"); group.bench_function("old", |b| b.iter(|| old_approach())); group.bench_function("new", |b| b.iter(|| new_approach())); group.finish(); // Output shows statistical comparison ``` --- ## Summary 1. **Use language-specific tools** — They handle warm-up, statistics, and optimization barriers 2. **Measure what matters** — Don't let the compiler cheat or I/O dominate 3. **Use statistics** — Single measurements are meaningless 4. **Separate setup from measurement** — Don't include allocations in your timings 5. **Compare with significance** — Use tools like benchstat or Criterion's comparison features For language-specific guidance, use the appropriate benchmark skill.