Search code examples
testinggobenchmarking

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,


Solution

  • 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).