I wrote two functions and now I would love to find out, which of them is faster. How can I find it out, which one is faster?
How can I find out by testing, which one is faster? Do go provide a timer for that?
I wrote two functions and now I would love to find out, which of them is faster. How can I find it out, which one is faster?
How can I find out by testing, which one is faster? Do go provide a timer for that?
Even better, Go provides a built in benchmark and testing functionality!
Create a file named something_test.go (must have the _test part).
func BenchmarkFunc1(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = Func1()
}
}
func BenchmarkFunc2(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = Func2()
}
}
Then simply run: go test -bench=. -benchmem
It will print how long each function took and memory usage / allocations.
Ref: