如何使用基准的时间价值

问题描述 投票:6回答:1

我在Go中为我的国际象棋引擎写了一个基准:

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个回答
9
投票

您可以使用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
© www.soinside.com 2019 - 2024. All rights reserved.