DEV Community

Cover image for Measure function execution time in golang
Rubin
Rubin

Posted on

Measure function execution time in golang

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)
}

Enter fullscreen mode Exit fullscreen mode

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


}

Enter fullscreen mode Exit fullscreen mode

Top comments (2)

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

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