How can I efficiently measure function execution time in Go with millisecond precision?

Susan Sarandon
Release: 2024-11-12 05:22:02
Original
217 people have browsed it

How can I efficiently measure function execution time in Go with millisecond precision?

Measuring Function Execution Time in Go with Millisecond Precision

One of the challenges in Go is determining the runtime of a function and reporting it in milliseconds.

Solution: Leveraging Go's defer

Go's defer statement provides a convenient solution for timing functions. Here's how it can be achieved:

Step 1: Define Utility Functions

Define the following utility functions in Go 1.x:

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

Step 2: Time Your Function

To time a function named someFunction, wrap it with the trace() and un() calls as follows:

func someFunction() {
    defer un(trace("SOME_ARBITRARY_STRING_SO_YOU_CAN_KEEP_TRACK"))

    // Do your function logic here
}
Copy after login

Explanation

The trace() function is called at the beginning of the function, recording the start time. The un() function is deferred to the end of the function, measuring the elapsed time and printing it to the log with millisecond precision.

Customizing Time Measurement

This technique can be modified to measure other time units such as nanoseconds or microseconds by adjusting the endTime.Sub(startTime) calculation.

By leveraging Go's defer statement, you can easily and accurately measure function execution times in milliseconds, providing valuable insights for performance optimization.

The above is the detailed content of How can I efficiently measure function execution time in Go with millisecond precision?. 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