From 59ef3d55eb1e2f92eb8c971efe5efe956fcdd6f2 Mon Sep 17 00:00:00 2001 From: Radu Berinde Date: Tue, 29 Oct 2024 11:38:05 -0700 Subject: [PATCH] crtime: add MonoFromTime method This is useful when we have a `time.Time` that we can't change to use `Mono`, for example `ctx.Deadline()`. --- crtime/monotonic.go | 6 ++++++ crtime/monotonic_test.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 crtime/monotonic_test.go diff --git a/crtime/monotonic.go b/crtime/monotonic.go index caf8eda..5124ae4 100644 --- a/crtime/monotonic.go +++ b/crtime/monotonic.go @@ -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 diff --git a/crtime/monotonic_test.go b/crtime/monotonic_test.go new file mode 100644 index 0000000..d386f90 --- /dev/null +++ b/crtime/monotonic_test.go @@ -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) + } +}