Home > Article > Backend Development > Why Does Measuring Deferred Function Execution Time in Go Return Unexpected Results?
Measuring Function Execution Time with Deferred Functions in Go
In Go, deferred functions provide a convenient mechanism to delay the execution of a function until the surrounding function returns. However, printing the time taken to execute a deferred function sometimes returns unexpected results.
Issue:
Consider the following sum() function that tries to calculate the execution time using a deferred function:
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) }
Running this code results in printing 0 for the execution time.
Solution:
The issue arises because the arguments to the deferred function are evaluated when the function is deferred, not when it is executed. To fix this, use an anonymous function to capture the current value of start and defer the execution of that anonymous function:
defer func() { fmt.Println(time.Now().Sub(start)) }()
By using an anonymous function, the value of start is evaluated at the time the deferred function is executed.
Further Considerations:
If you require more customization or flexibility, consider encapsulating the timing logic in a reusable function. This approach provides a more modular and reusable solution.
The above is the detailed content of Why Does Measuring Deferred Function Execution Time in Go Return Unexpected Results?. For more information, please follow other related articles on the PHP Chinese website!