知识卡片
基准应避免测到被消除的工作
固定输入的小函数可能被编译器预先算出,基准看似零耗时却没有测到真实路径。可用black_box等提示减少不真实优化,并检查生成代码与真实负载。该提示不强制编译器采取某种行为,测量仍需控制输入、环境与统计误差。
这张卡片看不懂?
这张卡片的反馈已满 10 条,暂时无法继续提交。
已有反馈 · 0 / 10 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 5. Tooling Benchmarks · 查看原书依据
black_box function can help with this; it’s an identity function whose implementation the compiler is “encouraged, but not required” (their italics) to pessimize. Moving the benchmark code to use this hint: #[bench] fn bench_factorial(b: &mut test::Bencher) { b.iter(|| { let result = factorial(std::hint::black_box(15)); assert_eq!(result, 1_307_674_368_000);
参考来源
- 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第5章《Benchmarks》(spine9;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch05.html;u156-ch05-026)。
- 结论依据:原文在“black_box”附近的定义、例子或代码支撑本卡核心说明:固定输入的小函数可能被编译器预先算出,基准看似零耗时却没有测到真实路径。边界按已读前提解释;示例未执行。
- 原始内容:black_box function can help with this; it’s an identity function whose implementation the compiler is “encouraged, but not required” (their italics) to pessimize. Moving the benchmark code to use this hint: #[bench] fn bench_factorial(b: &mut test::Bencher) { b.iter(|| { let result = factorial(std::hint::black_box(15)); assert_eq!(result, 1_307_674_368_000);