Why my Rust benchmarks were wrong, or how to use std:hint:black_box? (2022)
3 months ago
- #Optimization
- #Rust
- #Benchmarking
- The blog post discusses the correct use of `std::hint::black_box` in Rust benchmarks to prevent compiler optimizations from skewing results.
- It explains how the `black_box` function works by forcing the compiler to treat values as volatile, preventing optimizations around benchmarked code.
- The post provides examples of incorrect benchmarking, where the compiler optimizes away the code being measured, leading to misleadingly fast results.
- It compares different implementations of `black_box`, including the standard library's intrinsic and a more effective assembly-based version.
- The author demonstrates the impact of `black_box` on real-world benchmarks, such as `char::to_digit` and `str::parse::<f64>`, showing how missing `black_box` can lead to incorrect measurements.
- The post concludes with updated benchmark results after applying `black_box` correctly, showing more accurate performance measurements.
- It suggests that benchmarking is still valuable despite its imperfections and recommends tools like profiling and Compiler Explorer for optimization.