2

A defer statement defers the execution of a function until the surrounding function returns. However, if I try to print the time taken to execute the following function, it always prints 0.

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

    //expecting to print non zero value but always gets 0
    defer fmt.Println(time.Now().Sub(start))

    sum := 0
    for i := 1; i < 101; i++ {
        sum += i
    }
    time.Sleep(1 * time.Second)
    fmt.Println(sum)
}

Snippet: https://play.golang.org/p/46dxtS5beET

theblackpearl
  • 1,164
  • 3
  • 15
  • 34
  • 1
    This is covered in the tour: https://tour.golang.org/flowcontrol/12 "The deferred call's arguments are evaluated immediately" – Adrian Jan 31 '19 at 14:19

1 Answers1

10

The arguments to the deferred function are evaluated at the point the function is deferred. Use the following code to evaluate the elapsed time as you expect:

defer func() { fmt.Println(time.Now().Sub(start)) }()

An answer to a related question describes how to encapsulate the timing logic in a reusable function.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242