In Go, defer statements allow you to postpone the execution of a function until the surrounding function returns. However, when attempting to print the execution time of a function using defer, it may return 0. Let's examine this behavior and its solution.
Consider the following code snippet:
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) }
Even after sleeping for a second, deferring the time difference calculation always prints 0. Why does this happen?
The issue arises because the arguments to the deferred function are evaluated at the point the function is deferred. By the time the deferred function executes, the surrounding function has already returned, and the start variable is out of scope.
To fix this, we can create a closure that captures the current value of start. Here's the corrected code:
func sum() { start := time.Now() // Create a closure that captures the current value of start defer func() { fmt.Println(time.Now().Sub(start)) }() sum := 0 for i := 1; i < 101; i++ { sum += i } time.Sleep(1 * time.Second) fmt.Println(sum) }
Encapsulating the timing logic in a separate function can also improve code reusability.
The above is the detailed content of Why does deferring a time difference calculation in Go return 0 when attempting to measure function execution time?. For more information, please follow other related articles on the PHP Chinese website!