dopa53272 2017-01-25 21:24
浏览 64
已采纳

使用testing.Benchmark不会产生任何输出

I'm using testing.Benchmark to manually run a couple benchmarks but the result object is always empty.

Am I missing something here?

Here's an example:

package main

import "testing"

func main() {

    result := testing.Benchmark(func(parentB *testing.B) {
        parentB.Run("example", func(b *testing.B) {
            for n := 0; n < b.N; n++ {
                println("ok")
            }
        })
    })

    println(result.String())

}

This will print ok a couple times and then 0 0 ns/op but the benchmark clearly did run something.

  • 写回答

2条回答 默认 最新

  • doutang1873 2017-01-25 23:32
    关注

    I think you are doing everything right. Doc of testing.Benchmark() says:

    Benchmark benchmarks a single function. Useful for creating custom benchmarks that do not use the "go test" command.

    If f calls Run, the result will be an estimate of running all its subbenchmarks that don't call Run in sequence in a single benchmark.

    Looking into the implementation (Go 1.7.4):

    func Benchmark(f func(b *B)) BenchmarkResult {
        b := &B{
            common: common{
                signal: make(chan bool),
                w:      discard{},
            },
            benchFunc: f,
            benchTime: *benchTime,
        }
        if !b.run1() {
            return BenchmarkResult{}
        }
        return b.run()
    }
    

    This line:

        if !b.run1() {
            return BenchmarkResult{}
        }
    

    b.run1() is supposed to run your passed function once, and detect if it has sub-benchmarks. Yours has. It returns a bool whether more runs are needed. Inside run1():

    if b.hasSub || b.finished {
        // ...
        return true
    }
    

    It properly tells it has sub-benchmark, and Benchmark() –with noble simplicity– just returns an empty BenchmarkResult:

        if !b.run1() {
            return BenchmarkResult{}
        }
    

    I do believe that either this is a bug (or rather "incomplete" feature), or doc is incorrect. I suggest to file an issue here: https://github.com/golang/go/issues

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!