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

报告相同问题?

悬赏问题

  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答