Dec 192019

ADM

How to measure execution time in Golang

  • December 19 2019
  • ADM

 

 

How to measure execution time in Golang - golang

 

To mesure the time used by an application in Golang or of a code section the functions time.Now() and time.Since() can be used.

Code Section Timing

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println("Simple time measurement Golang Example")
	fmt.Println("")

	start := time.Now()

	//measuring the durration of the for loop
	for index := 0; index < 10; index++ {
		time.Sleep(500 * time.Millisecond)
	}
	elapsed := time.Since(start)
	fmt.Printf("The `for` loop took %s", elapsed)
}

Note: For this simple example it was used a for loop with 10 iterations having a 500 milliseconds sleep period.

Output

Simple time measurement Golang Example

The `for` loop took 5.000286s

Note: The result is this example is expected based on the loop. 10 iterations X 500 milliseconds = ~ 5 sec

Function Timing

To measure the execution time for a function it's easier to create an separate function that measure the time, and using defer to the measuring function in the beginning of the function we want to measure will ensure that the measuring function will be executed the last before leaving the current function.
package main

import (
	"fmt"
	"time"
)

func timeMeasurement(start time.Time) {
	elapsed := time.Since(start)
	fmt.Printf("Execution time: %s", elapsed)
}

func workerFunction() {
	defer timeMeasurement(time.Now())
	fmt.Println("Running 'workerFunction' function")
	for index := 0; index < 10; index++ {
		time.Sleep(500 * time.Millisecond)
	}
}

func main() {
	fmt.Println("Function time measurement Golang Example")
	fmt.Println("")

	workerFunction()
}

Output

Function time measurement Golang Example

Running 'workerFunction' function
Execution time: 5.001286s

Compile&Run

To compile the code navigate to the file location and run the following command.

$ go build timeMeasurement.go

Assuming that timeMeasurement.go is the name of your file.

Then depending on if you are on Linux or Windows the binary file is created.

To run the application execute the command.

Linux

$ ./timeMeasurement

Windows

c:\Users\adm\go\tutorials> timeMeasurement.exe

If you want to compile and run the application in one single step run the following command:

go run timeMeasurement.go

References