Search code examples
gobenchmarking

Strange output when running Go Benchmark


I'm trying to write a benchmark function for a simple echo program in Go (Exercise 1.3 from "The Go Programming Language" book). Here is the code:

package echo

import "testing"

func BenchmarkEcho1(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Echo1()
    }
}

When I run go test -bench=. the output is this:

PASS
BenchmarkEcho1-4    -test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
[...]
-test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
 1000000          1358 ns/op
ok      gopl.io/ch1/exercise1.3/echo    1.377s

There a lot of -test.bench=Echo1 between the first and the last lines. Why is this happening? What can I do to omit these lines?


Solution

  • You understand that b.N has a really big value and thus Echo1 gets executed many many times ? The only explanation is that Echo1 is printing the text you are seeing.

    Your Echo1() function probably contains something like this:

    var s string
    for i := 1; i < len(os.Args); i++ {
        s += os.Args[i]
    }
    fmt.Println(s)