Why Does Measuring Execution Time with Defer in Go Always Yield Zero?

Mary-Kate Olsen
Release: 2024-11-17 16:37:01
Original
349 people have browsed it

Why Does Measuring Execution Time with Defer in Go Always Yield Zero?

Measuring Execution Time in Go: Resolving the Defer Mystery

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

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

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!

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