Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benchmarking code with a StopWatch or similar

I'm trying to use Go package "time" to benchmark a function in my program. Been searching around, and people seem to use time.NanoSeconds() - but I think this function is no longer in the time package?

What I need is an easy way to start and stop a timer, and print out the value.

like image 679
shaz Avatar asked Apr 06 '12 19:04

shaz


Video Answer


1 Answers

Use the existing functionality of the testing package inside your *_test.go:

func BenchmarkMyFunc(b *testing.B) {
    for i := 0; i < b.N; i++ {
        myBecnhmarkedFunction()
    }
}

and invoke go test -bench RE (RE is a regexp to select the benches, like B as it means *B*) typically inside the package/tool directory

Or explicitly from any place in your code - use the Benchmark function.

like image 116
zzzz Avatar answered Oct 20 '22 18:10

zzzz