Home > Backend Development > Golang > Why Does Measuring Deferred Function Execution Time in Go Return Unexpected Results?

Why Does Measuring Deferred Function Execution Time in Go Return Unexpected Results?

Barbara Streisand
Release: 2024-11-20 11:47:51
Original
873 people have browsed it

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)
}
Copy after login

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)) }()
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template