Is there an efficient way to calculate execution time in golang?

Özgür Yalçın picture Özgür Yalçın · Aug 19, 2017 · Viewed 25.8k times · Source

I'm looking for the best way to calculate execution time in go.

func main() {
    start := time.Now()

    time.Sleep(time.Second * 2)

    //something doing here

    elapsed := time.Since(start)
    fmt.Printf("page took %s", elapsed)
}

The code above works fine.

But when I use templates, I have to write it again for each template function.

Is there an efficient way of calculating execution time, including templates?

Answer

Cerise Limón picture Cerise Limón · Aug 19, 2017

If you are timing an entire function, then you can use defer to eliminate some of the repetitive code.

func elapsed(what string) func() {
    start := time.Now()
    return func() {
        fmt.Printf("%s took %v\n", what, time.Since(start))
    }
}

func main() {
    defer elapsed("page")()  // <-- The trailing () is the deferred call
    time.Sleep(time.Second * 2)
}

playground example