douyue8364 2013-06-04 14:39
浏览 42
已采纳

改进测试。基准测试?

In learning about Go, I see that you can benchmark a function using fmt.Println(testing.Benchmark(BenchmarkFunction)), having set up the following:

func BenchmarkFunction(b *testing.B) {
    n := 42
    for i := 0; i < b.N; i++ {
        _ = Function(n)
    }
}

However, as the BenchmarkFunction code would be repeated for every benchmark of every method you would do this for (hence a code smell, in terms of DRY), is there a way that this could be rewritten using closures (or in some other manner) such that a benchmark of a function could be rewritten something like:

fmt.println(test.BenchmarkMyFunction(MyFunction(parameters...)))

and added either into my code or the testing library?

  • 写回答

3条回答 默认 最新

  • doushantun0614 2013-06-04 14:51
    关注

    Actually, this is not the right way to do benchmarks in Go.

    The actual standard is to put your benchmarking code into functions that have names BenchmarkXXX where XXX is whatever you like. Then you run go test -bench=. on the package that defines these files. go test is running all the benchmarks for you.

    If you have similar benchmarks with slightly different parameters, you can write a generic benchmarking function that is just called by all the other benchmarks:

    func genericBenchmarkFoo(b *testing.B, param int) { ... }
    

    And then you write a boilerplate function for each specific benchmark:

    func BenchmarkFoo1(b *testing.B) { genericBenchmarkFoo(b, 1) }
    func BenchmarkFoo2(b *testing.B) { genericBenchmarkFoo(b, 2) }
    func BenchmarkFoo3(b *testing.B) { genericBenchmarkFoo(b, 3) }
    func BenchmarkFoo4(b *testing.B) { genericBenchmarkFoo(b, 4) }
    

    You can find an example of this pattern in this package I wrote.

    Of course this is not exactly beautiful but I am afraid there is not an easier solution. It's clean coding however to find a small set of benchmarks that represent what you want to do.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比