⏲️ Measure execution time in Go

introduction time

Measuring the execution time of a given code block in Go consists of two steps that need to be done before and after a measured function. Before the function, you need to record the current time using time.Now(). Then, after executing the measured block, you can check how much time has elapsed since this time using time.Since() function.

package main

import (
    "log"
    "time"
)

func main() {
    start := time.Now()

    time.Sleep(2 * time.Second)

    log.Printf("main, execution time %s\n", time.Since(start))
}

Output:

2021/08/10 14:32:13 main, execution time 2.003051562s

You can shorten the measuring time procedure to one-liner using defer statement. The track function in the example below takes the name of the measured code block ("main") and returns a closure function that calculates the time elapsed since the call of the track. You only need to call this function at the end of the code block using defer statement that defers execution until the current function (main() in the example below) returns.

package main

import (
    "log"
    "time"
)

func track(name string) func() {
    start := time.Now()
    return func() {
        log.Printf("%s, execution time %s\n", name, time.Since(start))
    }
}

func main() {
    defer track("main")() // do not forget about the second parentheses
    time.Sleep(2 * time.Second)
}

Output:

2021/08/10 14:32:39 main, execution time 2.004788787s

😴 Sleep function in Go - pause the program execution

Learn how to pause the execution of a current Goroutine
introduction goroutine time

🖨️ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice

🧠 Print the memory address of a variable in Go

Learn how to find and print the address of a variable or pointer
introduction pointer slice