5

我在找:

1: startTime := time.Now()

2: // run something here that takes a while (measured in milliseconds)

3: duration := time.Since(startTime)

但是,我需要一些不受时钟时间变化影响的东西。如果在第 1 行和第 3 行之间调整时间,则持续时间将不准确。

解决这个问题的一些常用方法是什么,哪些 Go 库可能是相关的?

谢谢 :)

4

2 回答 2

2

对于 Linux (AMD64) goclock_gettime使用CLOCK_REALTIME. 请参阅time·now实施

你会想要一个单调的时钟(CLOCK_MONOTONICCLOCK_MONOTONIC_RAW),它是一个不会回到过去的时钟。在 Linux 中,手册页明确告诉您,CLOCK_MONOTONIC不能保证不会向前飞跃:

该时钟不受系统时间不连续跳跃的影响(例如,如果系统管理员手动更改时钟),但会受到 adjtime(3) 和 NTP 执行的增量调整的影响。

所以,在 Linux 下,最好的选择可能是CLOCK_MONOTONIC_RAW. 您可以为此使用 @MatrixFrog 提到的时钟包 。例子:

import (
    "fmt"
    "github.com/davecheney/junk/clock"
    "time"
)

func main() {
    start := clock.Monotonic.Now()
    // work
    end := clock.Monotonic.Now()

    duration := end.Sub(start)

    fmt.Println("Elapsed:", duration)
}

进一步阅读:

于 2013-10-30T03:11:24.667 回答
2

That lack of monotonic clock was detailed in issue 12914 (2015)

Since then, in August 2017 and Go 1.9, you now have a transparent Monotonic Time support:

The time package now transparently tracks monotonic time in each Time value, making computing durations between two Time values a safe operation in the presence of wall clock adjustments.
See the package docs and design document for details.

于 2017-08-27T17:23:24.757 回答