Accessing a benchmark's result

浪尽此生 提交于 2020-08-20 03:26:26

问题


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 far I have only been benchmarking my functions like this:

func BenchmarkMyFunction(b *testing.B) {
   // call to myFunction
}

And then running:

go test -bench=".*"

Here the results are printed to the console but I'd like to store them in a separate file. How can I use the BenchmarkResult type to do this?


回答1:


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.



来源:https://stackoverflow.com/questions/28045711/accessing-a-benchmarks-result

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!