Skip to content

Commit

Permalink
Merge pull request #11 from RaduBerinde/mono-to-utc
Browse files Browse the repository at this point in the history
crtime: add Mono.ToUTC
  • Loading branch information
RaduBerinde authored Dec 5, 2024
2 parents 793d93d + 94d24b6 commit 4a90b18
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
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))
}
})
}

0 comments on commit 4a90b18

Please sign in to comment.