doubi1818 2017-11-24 15:05
浏览 112
已采纳

Golang Benchmark表测试,我可以从b.Run()中提取func吗?

Following benchmark example tests in golang, I could for examlpe have this test:

// An example benchmark to benchmark a query based on different inputs
func Benchmark_GetProcessingCountForRegions(b *testing.B) {

    benchmarks := []struct {
        region string
    }{
        {"EU"},
        {"US"},
    }

    for _, bm := range benchmarks {
        b.Run(bm.region, func(bbb *testing.B) {
            for i := 0; i < bbb.N; i++ {
                taskDb.GetProcessingCountForRegion(bm.region)
            }
        })

    }
}

This is following default examples from the web and works for me; testing the taskDb package for performance on the GetProcessingCountForRegion query.

However for readability of this test I'm trying to extract the inside func, the one that sits inside b.Run(), like so, first extract the func and put it aside:

func GetProcessingCountForRegion(testingB *testing.B, region string) {
    for i := 0; i < testingB.N; i++ {
        taskDb.GetProcessingCountForRegion(region)
    }
}

and then use this func in the actual testfunc like so:

for _, bm := range benchmarks {
        b.Run(bm.region, GetProcessingCountForRegion(*b, bm.region))
}

However this gives a compile error: cannot use *b (type testing.B) as type *testing.B in argument to GetProcessingCountForRegion

removing the * from *b, gives the following compile error: GetProcessingCountForRegion(b, bm.region) used as value

So what I want is remove the func parameter from the B.Run(..) statement.

What am I missing?

  • 写回答

2条回答 默认 最新

  • douxing8855 2017-11-24 15:55
    关注

    I think I found an answer using a 'closure', that is, defining a func that returns a func(*testing.B), that can be used within the b.Run(..., namedMethod)..

    Code:

    func Benchmark_GetProcessingCountForRegions(b *testing.B) {
        benchmarks := []struct {
            region string
        }{
            {"EU"},
            {"US"},
        }
        for _, bm := range benchmarks {
            f := GetProcessingCountForRegion(bm.region)
            b.Run(bm.region, f)
        }
    }
    
    // GetProcessingCountForRegion is the closure function
    func GetProcessingCountForRegion(region string) func(*testing.B) {
        return func(b *testing.B) {
            for i := 0; i < b.N; i++ {
                taskDb.GetProcessingCountForRegion(region)
    
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?