user4211028
user4211028

Reputation:

Go benchmark by function name

I have this Benchmark function:

BenchmarkMyTest(b *testing.B) {
}

And I would like to run only this function not running all other tests, but the command never worked for me.

go test -bench='BenchmarkMyTest'
or
go test -run='BenchmarkMyTest'

What's the correct way of running one single benchmark function in Go? It says to use regex but I can't find any documentation.

Thanks,

Upvotes: 2

Views: 3050

Answers (2)

Jakub
Jakub

Reputation: 295

I found those answers incomplete, so here is more to the topic...

The following command runs all Benchmarks starting with BenchmarkMyTest (BenchmarkMyTest1, BenchmarkMyTest2, etc...) and also skip all tests with -run=^$ .

You can also specify a test duration with -benchtime 5s or you can force b.ReportAllocs() with -benchmem in order to get values like:

BenchmarkLogsWithBytesBufferPool-48     46416456                26.91 ns/op            0 B/op          0 allocs/op

the final command would be:

go test -bench=^BenchmarkMyTest . -run=^$ . -v -benchtime 5s -benchmem

Upvotes: 1

icza
icza

Reputation: 417612

Described at Command Go: Description of testing flags:

-bench regexp
    Run benchmarks matching the regular expression.
    By default, no benchmarks run. To run all benchmarks,
    use '-bench .' or '-bench=.'.

-run regexp
    Run only those tests and examples matching the regular
    expression.

So the syntax is that you have to separate it with a space or with the equal sign (with no apostrophe marks), and what you specify is a regexp:

go test -bench BenchmarkMyTest
go test -run TestMyTest

Or:

go test -bench=BenchmarkMyTest
go test -run=TestMyTest

Specifying exactly 1 function

As the specified expression is a regexp, this will also match functions whose name contains the specified name (e.g. another function whose name starts with this, for example "BenchmarkMyTestB"). If you only want to match "BenchmarkMyTest", append the regexp word boundary '\b':

go test -bench BenchmarkMyTest\b
go test -run TestMyTest\b

Note that it's enough to append it only to the end as if the function name doesn't start with "Benchmark", it is not considered to be a benchmark function, and similarly if it doesn't start with "Test", it is not considered to be a test function (and will not be picked up anyway).

Upvotes: 6

Related Questions