We have answer of your question!

100% solved queries, no empty question

Question: Improving testing.Benchmark for Go?


0

Advertisement


In learning about Go, I see that you can benchmark a function using fmt.Println(testing.Benchmark(BenchmarkFunction)), having set up the following:

func BenchmarkFunction(b *testing.B) {
    n := 42
    for i := 0; i < b.N; i++ {
        _ = Function(n)
    }
}

However, as the BenchmarkFunction code would be repeated for every benchmark of every method you would do this for (hence a code smell, in terms of DRY), is there a way that this could be rewritten using closures (or in some other manner) such that a benchmark of a function could be rewritten something like:

fmt.println(test.BenchmarkMyFunction(MyFunction(parameters...)))

and added either into my code or the testing library?

Question author Alistair-collins | Source

Answer


1


Advertisement


Actually, this is not the right way to do benchmarks in Go.

The actual standard is to put your benchmarking code into functions that have names BenchmarkXXX where XXX is whatever you like. Then you run go test -bench=. on the package that defines these files. go test is running all the benchmarks for you.

If you have similar benchmarks with slightly different parameters, you can write a generic benchmarking function that is just called by all the other benchmarks:

func genericBenchmarkFoo(b *testing.B, param int) { ... }

And then you write a boilerplate function for each specific benchmark:

func BenchmarkFoo1(b *testing.B) { genericBenchmarkFoo(b, 1) }
func BenchmarkFoo2(b *testing.B) { genericBenchmarkFoo(b, 2) }
func BenchmarkFoo3(b *testing.B) { genericBenchmarkFoo(b, 3) }
func BenchmarkFoo4(b *testing.B) { genericBenchmarkFoo(b, 4) }

You can find an example of this pattern in this package I wrote.

Of course this is not exactly beautiful but I am afraid there is not an easier solution. It's clean coding however to find a small set of benchmarks that represent what you want to do.

Answer author Fuz

Advertisement


Tickanswer.com is providing the only single recommended solution of the question Improving testing.Benchmark for Go? under the categories i.e testing , go , benchmarking , . Our team of experts filter the best solution for you.

Related Search Queries:

You may also add your answer!