gobenchmarking

Running benchmarks of subfolders from the project root


I have a project with a binary which entrypoint is located in ./cmd/<my-project>/main.go. I've added a benchmark in ./cmd/<my-project>/main_test.go.

Now I want to execute this benchmark from the repository root. I've tried to execute something like go test -bench=./cmd/<my-project>/main in various alternations (like for example go test -bench=./cmd/<my-project>/main_test.go or go test -bench=./cmd/<my-project>) but I couldn't get it to work.

The error I always get is:

can't load package: package github.com/<username>/<my-project>: no Go files in /home/<user>/go/src/github.com/<username>/<my-project>

and it's true, I have no *.go files in my project root.

All I came up with is changing into the directory first and run the benchmark with `go test -bench=.

However, as my program depends on the current working directory and the result is heavily depending on that it would be great to be able to execute it in another directory than the cmd/<my-project> one. (If this is good or not isn't part of the question :))

Update after the first comment:

I get it to run with go test -bench=. /cmd/<my-project> but the benchmark get's executed as if it would be run in the ./cmd/<my-project> directory. I've noticed similiar behaviour in 'normal tests' - but that wasn't a problem for me at any time.

So, my program does scan the current directory for files directories depending on the current working directory, this results in only two files found (main.go and main_test.go) where the benchmark isn't really helpful.


Solution

  • So to run the benchmarks:

    go test -bench=. ./cmd/<my-project>
    

    However, you are wanting to control the working directory, so really you want to run it from somewhere else. What you are looking for is the -c flag. It will create a binary instead of running the tests. You can then run the binary (and therefore your tests and benchmarks) where you want.

    go test -c ./cmd/my_proj
    my_proj.test -test.bench=.
    

    NOTE: Flags are prefixed with test. when you compile the tests.