Spearfisher
Spearfisher

Reputation: 8783

Accessing a benchmark's result

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?

Upvotes: 3

Views: 2531

Answers (1)

Intermernet
Intermernet

Reputation: 19388

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.

Upvotes: 5

Related Questions