I really interested in how much time is spending time to do this action. Does anybody have any best idea? or any library. I did with simple way, but it seems as wrong way. Because I did have more experience with workin on go
My have that code:
package main
import (
"fmt"
"time"
)
func main() {
var d int = 0
var beginTime = time.Now()
for i := 0; i < 100000; i++ {
for c := 0; c < 100; c++ {
d = 1
}
}
var endTime = time.Now()
fmt.Println(beginTime, endTime)
fmt.Println(time.Since(beginTime))
fmt.Println(d)
}
Use the built-in Benchmarks.
A sample benchmark function looks like this:
func BenchmarkHello(b *testing.B) { for i := 0; i < b.N; i++ { fmt.Sprintf("hello") } }
The benchmark function must run the target code b.N times. During benchark execution, b.N is adjusted until the benchmark function lasts long enough to be timed reliably. The output
BenchmarkHello 10000000 282 ns/op
means that the loop ran 10000000 times at a speed of 282 ns per loop.
EDIT: If you want to measure time of doing something at runtime, and not in your tests, your way looks fine to me.