How to use the time value of the standard

I wrote a test for my chess engine in Go:

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

I see this output when it starts:

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

I want to use the runtime (in this case 108737398 ns/op) to calculate another value, and also print it as a result of the test. In particular, I want to output nodes per second, which are given as a result of the call Perftdivided by the time by the call.

How do I access the test run time so that I can print my own results?

+6
source share
1 answer

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
+9

Source: https://habr.com/ru/post/1676716/


All Articles