Cookies management by TermsFeed Cookie Consent
Russia has invaded Ukraine and already killed tens of thousands of civilians, with many more raped or tortured. It's a genocide. We need your help. Let's fight back against the Russian regime.
Help Ukraine! Fight the Russian regime!

⏲️ Measure execution time in Go

introduction time

Please consider supporting us by disabling your ad blocker

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 time

📅 YYYY-MM-DD date format in Go

Learn how to format date without time
introduction time

♾️ Infinite loop in Go

Learn how to define a "while true" loop
introduction loop