douyong1850 2016-05-01 12:59
浏览 169
已采纳

Go testing.B基准能否防止不必要的优化?

I've recently started learning Go and I'm trying to implement a map that can be used concurrently by multiple groutines. I want to be able to compare my implementation to a simple sync.Mutex-protected map, or to something like this: https://github.com/streamrail/concurrent-map/blob/master/concurrent_map.go

From using Google Caliper, I assume that a naive approach for benchmarking would allow many unwanted optimizations to trash the actual results. Are the benchmarks that use testing.B employing some of the techniques to avoid that (after all both Go and Caliper are Google projects)? If yes, are they known? If not, what's the best way to microbenchmark in Go?

  • 写回答

3条回答 默认 最新

  • dongwuxie5112 2016-05-02 05:27
    关注

    Converting my comment to an answer.

    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

    The following page can also be useful.

    Compiler And Runtime Optimizations

    Another interesting read is

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

    Source1 Source2

    I'm not a 100% sure but the following should disable optimisations ? Someone with more experience needs to confirm it.

    go test -gcflags=-N -bench=.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行