Precisely Measuring Time Duration in Go
While most applications use the standard time package to measure time duration, it's crucial to address its limitations to obtain accurate results. time.Now() relies on the system time, which can be affected by time zone changes and clock synchronization with NTP servers.
To overcome these challenges, Go provides a "monotonic clock" that is unaffected by external time adjustments. Starting with Go 1.9, durations in Go automatically leverage this monotonic clock.
This means that the following code always computes a positive elapsed time of approximately 20 milliseconds, even if the wall clock changes during the timed operation:
start := time.Now() ... operation that takes 20 milliseconds ... t := time.Now() elapsed := t.Sub(start)
Other idioms like time.Since(start), time.Until(deadline), and time.Now().Before(deadline) are also resilient against wall clock resets.
Therefore, to precisely measure execution time in Go, simply use the time package's time.Now() and time.Sub() functions. These functions now ensure that elapsed time measurements are consistent and unaffected by system clock adjustments.
The above is the detailed content of How Can I Precisely Measure Execution Time in Go?. For more information, please follow other related articles on the PHP Chinese website!