Published on

How to measure the execution time of a function in Golang?

How to measure the execution time of a function in Golang?

Go: Function's execution time

To get execution time of a function in go we can use defer function because defer functions execute even if the code get an error so you always get the execution time.

Function's execution time Example

    // timer returns a function that prints the name argument and 
    // the elapsed time between the call to timer and the call to
    // the returned function. The returned function is intended to
    // be used in a defer statement:
    //
    func timer(name string) func() {
        start := time.Now()
        return func() {
            fmt.Printf("%s took %v\n", name, time.Since(start))
        }
    }

    func main() {
        defer timer("main")()  // <-- The trailing () is the deferred call
        time.Sleep(time.Second * 2)
    }   

    // prints: main took 2s