【问题标题】:How to use time value of benchmark如何使用基准的时间价值
【发布时间】:2017-10-07 09:49:17
【问题描述】:

我已经为我的围棋引擎编写了一个基准测试:

func BenchmarkStartpos(b *testing.B) {
    board := ParseFen(startpos)
    for i := 0; i < b.N; i++ {
        Perft(&board, 5)
    }
}

我在运行时看到这个输出:

goos: darwin
goarch: amd64
BenchmarkStartpos-4           10     108737398 ns/op
PASS
ok      _/Users/dylhunn/Documents/go-chess  1.215s

我想使用每次执行的时间(在本例中为108737398 ns/op)来计算另一个值,并将其作为基准测试的结果打印出来。具体来说,我想输出 每秒节点数,这是Perft 调用的结果除以每次调用的时间。

如何访问执行基准测试所用的时间,以便打印自己的派生结果?

【问题讨论】:

    标签: go benchmarking


    【解决方案1】:

    您可以使用testing.Benchmark() 函数手动测量/基准测试“基准”函数(具有func(*testing.B) 的签名),您会得到testing.BenchmarkResult 的值,这是一个包含所有您需要的详细信息:

    type BenchmarkResult struct {
        N         int           // The number of iterations.
        T         time.Duration // The total time taken.
        Bytes     int64         // Bytes processed in one iteration.
        MemAllocs uint64        // The total number of memory allocations.
        MemBytes  uint64        // The total number of bytes allocated.
    }
    

    每次执行的时间由BenchmarkResult.NsPerOp() 方法返回,你可以用它做任何你想做的事情。

    看这个简单的例子:

    func main() {
        res := testing.Benchmark(BenchmarkSleep)
        fmt.Println(res)
        fmt.Println("Ns per op:", res.NsPerOp())
        fmt.Println("Time per op:", time.Duration(res.NsPerOp()))
    }
    
    func BenchmarkSleep(b *testing.B) {
        for i := 0; i < b.N; i++ {
            time.Sleep(time.Millisecond * 12)
        }
    }
    

    输出是(在Go Playground上试试):

         100      12000000 ns/op
    Ns per op: 12000000
    Time per op: 12ms
    

    【讨论】:

    • 由于该解决方案包含main() 函数,它必须放在“主”包中,对吗?我的项目是一个库,所以没有主包,在 repo 中添加一个会导致人们难以通过go get 获取它。有什么解决办法吗?
    • @dylhunn 我提供了一个指向Go Playground 的链接,您可以在其中试用。拥有main() 功能,您可以开箱即用。你可以使用main()函数中的代码everywhere,显然也包括非main函数,也包括测试包。
    • @ixza 啊,我明白了。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2019-08-21
    • 2021-09-07
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多