DEV Community

loading...
Cover image for Measure function execution time in golang

Measure function execution time in golang

rubiin profile image Rubin ・1 min read

For some reason you may want to keep a track of how much long a function takes to do a certain task in golang, maybe for performance evaluation.Here is a function that tracks the execution time of a complete function call with this one-liner, which logs the result to the standard output.

func timeTrack(start time.Time, name string) {
    elapsed := time.Since(start)
    log.Printf("%s took %s", name, elapsed)
}

The usage is fairly simple and straight forward. Defer the call to this function before doing the actual function call.


package main

import "fmt"

func main() {

defer timeTrack(time.Now(), "Timer")

// your code goes here


}

Discussion (2)

pic
Editor guide
Collapse
therealkevinard profile image
Kevin Ard

I wrote a similar handler very early in my Go studies out of curiosity. I remember how blown away I was when I first saw decimal microseconds 🀯

Started when I honestly thought I'd made an error - I was sending messages to a rabbit backend and the in rate was orders of magnitude beyond what I expected. Lol thought I was skipping processing or something and spent HOURS step debugging out of distrust πŸ˜‚

Collapse
rubiin profile image
Rubin Author

same. I was also trying to measure the performance improvements with and without goroutines on a project