File tree Expand file tree Collapse file tree 2 files changed +25
-0
lines changed
Expand file tree Collapse file tree 2 files changed +25
-0
lines changed Original file line number Diff line number Diff line change @@ -44,6 +44,18 @@ func (m Mono) Elapsed() time.Duration {
4444 return time .Duration (NowMono () - m )
4545}
4646
47+ // ToUTC returns the UTC time corresponding to the monotonic time.
48+ //
49+ // The time is derived from the current wall clock, adjusted by the difference
50+ // in the monotonic clock values. Note that if the wall clock has been changed
51+ // since the Mono value was obtained, the result does not reflect the wall clock
52+ // at that point in time.
53+ func (m Mono ) ToUTC () time.Time {
54+ now := time .Now ()
55+ adjustment := time .Duration (m ) - now .Sub (startTime )
56+ return now .UTC ().Add (adjustment )
57+ }
58+
4759// MonoFromTime converts a time.Time to a Mono value. If the time has a
4860// monotonic component, it is used.
4961func MonoFromTime (t time.Time ) Mono {
Original file line number Diff line number Diff line change @@ -30,4 +30,17 @@ func TestMono(t *testing.T) {
3030 d := NowMono ()
3131 require .LE (t , b , c )
3232 require .LE (t , c , d )
33+
34+ t .Run ("ToUTC" , func (t * testing.T ) {
35+ const d = 50 * time .Millisecond
36+ const tolerance = time .Millisecond
37+
38+ start := NowMono ()
39+ expected := time .Now ().UnixNano ()
40+ time .Sleep (d )
41+ actual := start .ToUTC ().UnixNano ()
42+ if actual < expected - tolerance .Nanoseconds () || actual > expected + tolerance .Nanoseconds () {
43+ t .Fatalf ("actual - expected = %s" , time .Duration (actual - expected ))
44+ }
45+ })
3346}
You can’t perform that action at this time.
0 commit comments