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条)

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等