go - Go testing.B 基准测试是否可以防止不必要的优化?

标签 go microbenchmark caliper

我最近开始学习 Go,我正在尝试实现一个可以由多个 groutines 同时使用的映射。我希望能够将我的实现与一个简单的 sync.Mutex-protected map 或类似这样的东西进行比较:https://github.com/streamrail/concurrent-map/blob/master/concurrent_map.go

通过使用 Google Caliper,我假设一种天真的基准测试方法会允许许多不需要的优化破坏实际结果。使用 testing.B 的基准是否采用了一些技术来避免这种情况(毕竟 Go 和 Caliper 都是 Google 项目)?如果是,他们知道吗?如果不是,在 Go 中进行微基准测试的最佳方法是什么?

最佳答案

将我的评论转化为答案。

To be completely accurate, any benchmark should be careful to avoid compiler optimisations eliminating the function under test and artificially lowering the run time of the benchmark.

var result int

func BenchmarkFibComplete(b *testing.B) {
        var r int
        for n := 0; n < b.N; n++ {
                // always record the result of Fib to prevent
                // the compiler eliminating the function call.
                r = Fib(10)
        }
        // always store the result to a package level variable
        // so the compiler cannot eliminate the Benchmark itself.
        result = r
}

Source

以下页面也很有用。

Compiler And Runtime Optimizations

另一个有趣的读物是

One other interesting flag is -N, which will disable the optimisation pass in the compiler.

Source1 Source2

我不是 100% 确定但以下应该禁用优化?需要有经验的人来确认。

go test -gcflags=-N -bench=.

关于go - Go testing.B 基准测试是否可以防止不必要的优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36966947/

相关文章:

java - 如何在 Java1.6 中安装证书,以便从 Caliper 工具上传有效

java - 估计实现的实际(非理论)运行时复杂性

r - 意外结果 : microbenchmark

performance - 在 init 或处理函数中读取模板?

go - 将两个返回值传递给一个参数的函数

json - 可以在 Go 中获取 JSON 的值

java - 循环习语的奇怪 JIT 悲观化

c - BENCH_INNER : lmbench3. 0 src代码宏查询

java - 如何使用 Caliper 进行基准测试?

opengl - Go Lang OpenGL 简单形状 - 空白屏幕