Home >Backend Development >Golang >Why Does Measuring Execution Time with Defer in Go Always Yield Zero?
Defer statements await the completion of a function before executing their associated functions. However, printing the execution time of the following function using defer always yields zero:
func sum() { start := time.Now() // Expected 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) }
Issue:
defer evaluates the arguments of the deferred function when the containing function defers them. Therefore, start is evaluated immediately, before the loop or sleep.
Solution:
To measure elapsed time accurately, evaluate time.Now() inside the deferred function:
defer func() { fmt.Println(time.Now().Sub(start)) }()
By doing so, the time difference is calculated when the deferred function executes, ensuring accurate results.
Tip: Consider using a reusable function to encapsulate the timing logic for easier and more consistent measurement.
The above is the detailed content of Why Does Measuring Execution Time with Defer in Go Always Yield Zero?. For more information, please follow other related articles on the PHP Chinese website!