Measure function execution time in golang
Rubin

Rubin @rubiin

About: Self taught developer,FOSS lover, linux enthusiast

Location:
Kathmandu, Nepal
Joined:
Dec 17, 2017

Measure function execution time in golang

Publish Date: Jul 12 '20
6 2

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

Comments 2 total

  • Kevin Ard
    Kevin ArdJul 19, 2020

    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 😂

    • Rubin
      RubinJul 20, 2020

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

Add comment