为什么我的 Rust 基准测试结果不准确,或者如何使用 std::hint::black_box? (2022)
Why my Rust benchmarks were wrong, or how to use std::hint::black_box? (2022)

原始链接: https://gendignoux.com/blog/2022/01/31/rust-benchmarks.html

## Rust 基准测试:深入研究 `std::hint::black_box` 本文深入探讨了 Rust 代码基准测试的复杂性,特别是 `std::hint::black_box` 函数及其对准确测量的影响。作者最初观察到,对于看似复杂的操作,基准测试结果出乎意料地快(报告为瞬时)。这促使他们调查 Rust 的基准测试工具——主要是 `#[bench]` 属性和 `Bencher` API——的实际工作原理。 Rust 基准测试的核心涉及在循环中重复执行代码并测量经过的时间。`black_box` 的目的是防止编译器优化掉被基准测试的代码。然而,作者发现仅仅用 `black_box` 包装函数的*结果*是不够的;编译器仍然可以积极地进行优化。 真正的准确性要求将 `black_box` 应用于被基准测试函数的*输入和输出*,从而有效地防止消除计算本身的优化。使用 Compiler Explorer 检查汇编代码揭示了编译器如何绕过缺乏这种输入-输出限制的基准测试。作者通过示例演示了这一点,包括标准库函数和自定义有限域算术。 最终,本文强调了在基准测试时理解编译器优化的重要性,并提供了编写可靠 Rust 基准测试的实用建议。虽然 `black_box` 是一个有用的工具,但需要小心使用才能确保有意义的结果,并且性能分析仍然是代码优化的一种有价值的补充技术。

Hacker News 新闻 | 过去 | 评论 | 提问 | 展示 | 招聘 | 提交 登录 为什么我的 Rust 基准测试出错,或者如何使用 std::hint::black_box? (2022) (gendignoux.com) 6 分,aw1621107 发表于 2 小时前 | 隐藏 | 过去 | 收藏 | 1 条评论 aw1621107 发表于 2 小时前 [–] 完整标题是“为什么我的 Rust 基准测试出错,或者如何[正确地]使用 std::hint::black_box?”,但我不得不删除一些内容以使标题适应。回复 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请 YC | 联系 搜索:
相关文章

原文

In a previous blog post, I described some benchmarks I wrote for a program written in Rust. While presenting the results, I mentioned a strange behavior: things that should have been very fast (a few nanoseconds) were reported as instantaneous. I wrote that it was probably fine given that the bigger benchmarks (above 10 nanoseconds) were seemingly working well, following the expected asymptotic behavior. However, this prompted me to dig deeper to understand what was going on under the hood.

In this blog post, I’ll present my findings, including some misconceptions I had about the std::hint::black_box function, and how to use this hint function properly to benchmark your code as faithfully as possible.