问题
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