Home > Backend Development > Golang > How Can We Accurately Measure Function Execution Time Using Go\'s `defer` Statement?

How Can We Accurately Measure Function Execution Time Using Go\'s `defer` Statement?

Linda Hamilton
Release: 2024-11-17 14:49:02
Original
761 people have browsed it

How Can We Accurately Measure Function Execution Time Using Go's `defer` Statement?

Defer Timing: Achieving Accurate Time Measurement in Go

In Go, the defer statement allows us to delay the execution of a function until the surrounding function returns. While this feature can be beneficial, it can create challenges when attempting to measure the execution time of a function.

Consider the following 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

In this function, we intend to print the time taken to execute the inner loop. However, our expectation is not met, and the output always shows 0.

The reason for this discrepancy lies in the evaluation of arguments for the deferred function. The arguments are evaluated when the function is deferred, not when it is actually executed. By the time the deferred function runs (when the surrounding function returns), the loop has already completed, resulting in an elapsed time of 0.

To resolve this issue and obtain a non-zero elapsed time, we can modify the code as follows:

defer func() { fmt.Println(time.Now().Sub(start)) }()
Copy after login

By wrapping the deferred function call in an additional anonymous function, we defer the execution of the code that evaluates the start time. This ensures that it is evaluated and updated just before the deferred function call executes.

This approach allows us to accurately measure the execution time of the inner loop:

start time: 2023-02-07 16:25:42.39378981 +0000 UTC
end time: 2023-02-07 16:25:42.40889486 +0000 UTC
time taken: 15.11010505ns
Copy after login

The above is the detailed content of How Can We Accurately Measure Function Execution Time Using Go\'s `defer` Statement?. 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