doukangbin9698 2017-05-09 07:31
浏览 32
已采纳

如何使用基准时间值

I have written 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)
    }
}

I see this output when it runs:

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

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

How can I access the time the benchmark took to execute, so I can print my own derived results?

  • 写回答

1条回答 默认 最新

  • douhun7609 2017-05-09 07:44
    关注

    You may use the 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, which is a struct with all the details you need:

    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 time per execution is returned by the BenchmarkResult.NsPerOp() method, you can do whatever you want to with that.

    See this simple example:

    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)
        }
    }
    

    Output is (try it on the Go Playground):

         100      12000000 ns/op
    Ns per op: 12000000
    Time per op: 12ms
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?