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 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决