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

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

报告相同问题?

悬赏问题

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