Timing for lazy people

The laziest way to time a function in Go
2022-12-04 golang

Ever wanted to time a Go function but didn’t feel like writing a proper benchmark?

A stop watch isn’t the best way to benchmark a function

When in a hurry, copy paste this code somewhere:

func timeIt(s string) func() {
   start := time.Now()
   return func() {
       log.Printf("%s%s", s, time.Since(start))
   }
}

Then at top of your function, add a timeIt call, calling the returned function as a defer:

func foo() {
    defer timeIt("here")()

    // timed code ...
}