Cookies management by TermsFeed Cookie Consent

⏲️ 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

Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

😴 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