Home >Backend Development >Golang >Why Does Measuring Execution Time with Defer in Go Always Yield Zero?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-17 16:37:01421browse

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)
}

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!

Statement:
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