gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:52:23 26 4
gpt4 key购买 nike

我最近开始学习 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com