Accessing a benchmark's result

后端 未结 1 887
南笙
南笙 2021-01-22 14:42

I\'ve seen there is a struct testing.BenchmarkResult in Go to accesss the result of a benchmark but I found very little documentation or examples to help me use it.

So

相关标签:
1条回答
  • 2021-01-22 15:16

    For example:

    package main
    
    import (
        "fmt"
        "testing"
        "time"
    )
    
    func Add(a, b int) int {
        time.Sleep(10 * time.Microsecond) // Just to make the test take some time
        return a + b
    }
    
    func BenchAdd(b *testing.B) {
        for i := 0; i < b.N; i++ {
            _ = Add(1, 2)
        }
    }
    
    func main() {
        res := testing.Benchmark(BenchAdd)
        fmt.Printf("%s\n%#[1]v\n", res)
    }
    

    Produces:

      120000         10000 ns/op
    testing.BenchmarkResult{N:120000, T:1200000000, Bytes:0, MemAllocs:0x0, MemBytes:0x0, Extra:map[string]float64{}}
    

    Playground.

    You can easily write these results out to a file using ioutil.WriteFile. Playground w/ WriteFile.

    0 讨论(0)
提交回复
热议问题