2

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?

Dave C
  • 7,729
  • 4
  • 49
  • 65
Spearfisher
  • 8,445
  • 19
  • 70
  • 124
  • 2
    Just redirect stdout to a file in your shell. – Volker Jan 20 '15 at 12:47
  • Note benchmarks need to look over `b.N` to be useful. See https://golang.org/pkg/testing/#hdr-Benchmarks – Dave C Dec 29 '19 at 15:53
  • Also, as recommended in the documentation, you can use just `go test -bench=.` to run all benchmarks. This avoids the need to escape/quote `*` from the shell. – Dave C Dec 29 '19 at 16:09
  • There is also the `-json` flag to `go test` (added in [Go 1.10](https://golang.org/doc/go1.10#test)) which outputs results in a machine parse-able JSON format. – Dave C Dec 29 '19 at 16:21

1 Answers1

4

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.

Dave C
  • 7,729
  • 4
  • 49
  • 65
Intermernet
  • 18,604
  • 4
  • 49
  • 61