vendredi 24 août 2018

How to properly StartTime and StopTime in golang benchmark?

I wrote a benchmark to test the speed of two Fibonacci number generators, and the source code is here on github.

func BenchmarkFib(b *testing.B) {
    fibFuncs := []struct {
        name string
        f    func(int) int
    }{
        {"recursive", fibRecu},
        {"iterative", fibIter},
    }
    for _, fibFunc := range fibFuncs {
        // calculate k'th Fibonacci number
        for k := 10; k < 1001; k *= 10 {
            b.Run(fmt.Sprintf("%s Fib %v", fibFunc.name, k), func(b *testing.B) {
                for n := 0; n < b.N; n++ {
                    //                  b.StopTimer()
                    // reset the memo
                    memo = map[int]int{0: 0, 1: 1, 2: 1}
                    //                  b.StartTimer()
                    fibFunc.f(k)
                }
            })
        }
    }
}

As it is, the benchmark works and the output is

nos (master) fibonacci $ go test -bench .
goos: linux
goarch: amd64
pkg: github.com/nosarthur/dynamicP/fibonacci
BenchmarkFib/recursive_Fib_10-4                  1000000              1256 ns/op
BenchmarkFib/recursive_Fib_100-4                  100000             18256 ns/op
BenchmarkFib/recursive_Fib_1000-4                  10000            206109 ns/op
BenchmarkFib/iterative_Fib_10-4                 10000000               218 ns/op
BenchmarkFib/iterative_Fib_100-4                 5000000               292 ns/op
BenchmarkFib/iterative_Fib_1000-4                2000000               881 ns/op
PASS
ok      github.com/nosarthur/dynamicP/fibonacci 12.208s

However, I added b.StopTime() and b.StartTime() to exclude the time for resetting the memo. With these two lines un-commented, the benchmark hangs, and the partial output is

nos (master *) fibonacci $ go test -bench .
goos: linux
goarch: amd64
pkg: github.com/nosarthur/dynamicP/fibonacci
BenchmarkFib/recursive_Fib_10-4                  1000000              2139 ns/op
BenchmarkFib/recursive_Fib_100-4                  100000             24775 ns/op
BenchmarkFib/recursive_Fib_1000-4                   5000            239197 ns/op
BenchmarkFib/iterative_Fib_10-4                 ^Csignal: interrupt
FAIL    github.com/nosarthur/dynamicP/fibonacci 269.067s

What is the proper way to exclude the memo resetting? My go version is 1.10.1

Aucun commentaire:

Enregistrer un commentaire