1024programmer Java Go: time value using benchmark

Go: time value using benchmark

I wrote a benchmark for my chess engine in Go:

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

When running I see this output:

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

I want to use the time of each execution (in this case 108737398 ns/op) to calculate another value and print it out as the result of the benchmark. Specifically, I want to output nodes per second, which is given as the result of a Perft call divided by the time of each call.

How can I access the time of the benchmark execution so I can print my own derived results?

1> icza..:

You can manually measure/benchmark using the testing.Benchmark() function Test a “benchmark” function (with signature func(*testing.B)) and get the result as a value to testing.BenchmarkResult, which is a function with all the details you need The structure of information:

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.

The BenchmarkResult.NsPerOp() method returns the time of each execution, and you can use this method to perform any operation.

Look at this simple example:

func main() {
     res := testing.Benchmark(BenchmarkSleep)
     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)

The output is (try it on Go Playground):

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

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/764810

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us


Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top