如何使用基准时间价值
How to use time value of benchmark
我已经用 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
)来计算另一个值,并将其打印为基准测试的结果。具体来说,我想输出 nodes per second,这是 Perft
调用除以每次调用时间的结果。
如何获取执行基准测试所花费的时间,以便打印我自己的派生结果?
您可以使用 testing.Benchmark()
function to manually measure / benchmark "benchmark" functions (that have the signature of func(*testing.B)
), and you get the result as a value of 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
我已经用 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
)来计算另一个值,并将其打印为基准测试的结果。具体来说,我想输出 nodes per second,这是 Perft
调用除以每次调用时间的结果。
如何获取执行基准测试所花费的时间,以便打印我自己的派生结果?
您可以使用 testing.Benchmark()
function to manually measure / benchmark "benchmark" functions (that have the signature of func(*testing.B)
), and you get the result as a value of 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