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:
You could write a benchmark for each function.
See for instance "How to write benchmarks in Go"
// from source_test.go
func BenchmarkFunction1(b *testing.B) {
// run the Function1 function b.N times
for n := 0; n < b.N; n++ {
Function1(10)
}
}
Repeat for Function2
and check the results with go test -bench=.