Skip to content

Commit

Permalink
crtime: add MonoFromTime method
Browse files Browse the repository at this point in the history
This is useful when we have a `time.Time` that we can't change to use
`Mono`, for example `ctx.Deadline()`.
  • Loading branch information
RaduBerinde committed Oct 29, 2024
1 parent f5792c2 commit 59ef3d5
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
6 changes: 6 additions & 0 deletions crtime/monotonic.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ func (m Mono) Elapsed() time.Duration {
return time.Duration(NowMono() - m)
}

// 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 {
return Mono(t.Sub(startTime))
}

// We use startTime as a reference point against which we can call
// time.Since(). This solution is suggested by the Go runtime code:
// https://github.com/golang/go/blob/889abb17e125bb0f5d8de61bb80ef15fbe2a130d/src/runtime/time_nofake.go#L19
Expand Down
34 changes: 34 additions & 0 deletions crtime/monotonic_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright 2024 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.

package crtime

import (
"testing"
"time"
)

func TestMono(t *testing.T) {
a := NowMono()
time.Sleep(10 * time.Millisecond)
b := NowMono()
if delta := b.Sub(a); delta < 9*time.Millisecond {
t.Errorf("expected 10+ms, got %s", delta)
}
c := MonoFromTime(time.Now())
d := NowMono()
if c < b || c > d {
t.Errorf("expected %d <= %d <= %d", b, c, d)
}
}

0 comments on commit 59ef3d5

Please sign in to comment.