Go:使用基准的时间值

dyl*_*unn 6 benchmarking go

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

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

运行时我看到这个输出:

goos: darwin
goarch: amd64
BenchmarkStartpos-4           10     108737398 ns/op
PASS
ok      _/Users/dylhunn/Documents/go-chess  1.215s
Run Code Online (Sandbox Code Playgroud)

我想使用每次执行的时间(在这种情况下108737398 ns/op)来计算另一个值,并将其作为基准测试的结果打印出来.具体来说,我希望每秒输出节点,这是作为Perft呼叫结果除以每次呼叫的时间给出的.

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

icz*_*cza 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.
}
Run Code Online (Sandbox Code Playgroud)

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

     100      12000000 ns/op
Ns per op: 12000000
Time per op: 12ms
Run Code Online (Sandbox Code Playgroud)