clockwork icon indicating copy to clipboard operation
clockwork copied to clipboard

RealClock Since&Until optimizations

Open OS-M opened this issue 6 months ago • 1 comments

My implementation gives a way for time package optimizations:

// Since returns the time elapsed since t.
// It is shorthand for time.Now().Sub(t).
func Since(t Time) Duration {
	if t.wall&hasMonotonic != 0 {
		// Common case optimization: if t has monotonic time, then Sub will use only it.
		return subMono(runtimeNano()-startNano, t.ext)
	}
	return Now().Sub(t)
}

// Until returns the duration until t.
// It is shorthand for t.Sub(time.Now()).
func Until(t Time) Duration {
	if t.wall&hasMonotonic != 0 {
		// Common case optimization: if t has monotonic time, then Sub will use only it.
		return subMono(t.ext, runtimeNano()-startNano)
	}
	return t.Sub(Now())
}

Which leads to greatly decreased latencies of these methods

OS-M avatar Aug 25 '25 13:08 OS-M

@jonboulle hello Nell, could you please have a look?

OS-M avatar Aug 28 '25 15:08 OS-M