Do Not Optimize Away
2 days ago
- #compiler-optimization
- #anti-optimization
- #benchmarking
- Compilers optimize code by replacing computations with equivalent formulas, which can interfere with benchmarking.
- Benchmarking pitfalls include compilers optimizing away unused results and constant-folding parts of computations.
- Languages provide functions like Rust's `hint::black_box` or Zig's `mem.doNotOptimizeAway` to prevent optimization, but their semantics are unclear.
- A better approach is to use runtime-overridable input parameters and print or hash results to ensure computations aren't optimized away.
- This method also helps catch optimization errors by verifying the hash of results.