How Long Does a Function Take: Measuring Execution Time

· 189 words · 1 minute read

We often need to measure execution time in programming, as it helps us understand the programs we’re working with and knowing where potential bottlenecks are occurring.

In Go, we are able to use the time package and the defer keyword to run our time tracking function at the end of our long function. The parameters will be calculated at the beginning of the function (thus freezing the start time). Once the deferred function is running, all we need to do is show the difference in start time and current time.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
    "log"
    "time"
)

func main() {
    LongRunningFunction()
}

func LongRunningFunction() {

    // Use our time taken function to log the current time with the defer 
    // so it will actually run at the end at the end of this function.
    defer TimeTaken(time.Now(), "LongRunningFunction")

    // ... to illustrate pause.
    time.Sleep(2 * time.Second)

}

func TimeTaken(t time.Time, name string) {
    elapsed := time.Since(t)
    log.Printf("TIME: %s took %s\n", name, elapsed)
}

Example:

Example of Measuring Function Execution Time

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!