Home > Backend Development > Golang > How to Measure Function Runtime in Go Using the Defer Feature?

How to Measure Function Runtime in Go Using the Defer Feature?

DDD
Release: 2024-11-17 09:12:03
Original
409 people have browsed it

How to Measure Function Runtime in Go Using the Defer Feature?

Measuring Function Runtime in Go

In Go, a simple way to measure the execution time of a function is to leverage the defer feature.

Implementation

  1. Define the following helper functions:
func trace(s string) (string, time.Time) {
    log.Println("START:", s)
    return s, time.Now()
}

func un(s string, startTime time.Time) {
    endTime := time.Now()
    log.Println("  END:", s, "ElapsedTime in seconds:", endTime.Sub(startTime))
}
Copy after login
  1. Use these functions in the target function:
func someFunction() {
    defer un(trace("SOME_ARBITRARY_STRING_SO_YOU_CAN_KEEP_TRACK"))

    // Perform the function's intended operations here...
}
Copy after login

Explanation

  • The trace() function is called at the beginning of the function and returns the function name and the current time.
  • The defer un statement defers the execution of un() until the end of the function.
  • When un() is executed, it calculates the elapsed time using the difference between the current time and the start time obtained from trace().
  • The time is logged in milliseconds.

Note:

  • This approach is not atomic-clock accurate due to the logging statements. For more precise timing, consider using specific profiling tools.

The above is the detailed content of How to Measure Function Runtime in Go Using the Defer Feature?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template