Golang: Measuring execution time using a deferred function

Simple timing in Golang

func main() {
start := time.Now()
time.Sleep(time.Second * 3)
elapsed := time.Since(start)
fmt.Printf("Time took %s", elapsed)
}

A Timing function using a deferred function

import (
"fmt"
"time"
)
func main() {
defer MeasureTime("Task One")()
time.Sleep(time.Second * 3)
fmt.Println("End")
}
func MeasureTime(process string) func() {
fmt.Printf("Start %s\n", process)
start := time.Now()
return func() {
fmt.Printf("Time taken by %s is %v\n", process, time.Since(start))
}

}
Start Task One
End
Time taken by Task One is 3.001237375s

How does this work?

func MeasureTime(process string) func() {
fmt.Printf("Start %s\n", process)
start := time.Now()
return func() {
fmt.Printf("Time taken by %s is %v\n", process, time.Since(start))
}

}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Able Lv

Cloud Infrastructure Engineer @Airwallex: Kubernetes, DevOps, Terraform, Istio, Go, and Cloud-Native stuff