Golang: Measuring execution time using a deferred function

Simple timing in Golang

A simple way to measure execution time in Golang is to use the time.Now() and time.Since() functions:

A Timing function using a deferred function

Here is an example program using a deferred function MeasureTime() to measure execution time:

Here’s what the output looks like:

How does this work?

A defer statement defers the execution of the specified until the surrounding function returns.

However, why does it output “Start Task One” first?

The Golang specification says:

Each time a “defer” statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked.

In the above code, the MeasureTime function returns a function type. Since defer statement needs to evaluate the statement, it will actually execute the MeasureTime function to get the return function. So the code prints out “Start” first.

If a deferred function does not return a function type, then the function body will not be executed until enclosing function returns.



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

Able Lv


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