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 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件