Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

crtime: add Mono.ToUTC #11

Merged
merged 1 commit into from
Dec 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions crtime/monotonic.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,18 @@ func (m Mono) Elapsed() time.Duration {
return time.Duration(NowMono() - m)
}

// ToUTC returns the UTC time corresponding to the monotonic time.
//
// The time is derived from the current wall clock, adjusted by the difference
// in the monotonic clock values. Note that if the wall clock has been changed
// since the Mono value was obtained, the result does not reflect the wall clock
// at that point in time.
func (m Mono) ToUTC() time.Time {
now := time.Now()
adjustment := time.Duration(m) - now.Sub(startTime)
return now.UTC().Add(adjustment)
}

// MonoFromTime converts a time.Time to a Mono value. If the time has a
// monotonic component, it is used.
func MonoFromTime(t time.Time) Mono {
Expand Down
13 changes: 13 additions & 0 deletions crtime/monotonic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,17 @@ func TestMono(t *testing.T) {
d := NowMono()
require.LE(t, b, c)
require.LE(t, c, d)

t.Run("ToUTC", func(t *testing.T) {
const d = 50 * time.Millisecond
const tolerance = time.Millisecond

start := NowMono()
expected := time.Now().UnixNano()
time.Sleep(d)
actual := start.ToUTC().UnixNano()
if actual < expected-tolerance.Nanoseconds() || actual > expected+tolerance.Nanoseconds() {
t.Fatalf("actual - expected = %s", time.Duration(actual-expected))
}
})
}
Loading