1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use std::{
ops::{Add, AddAssign, Sub, SubAssign},
time::Duration,
};
use web_time::{SystemTime, UNIX_EPOCH};
/// A measurement of a monotonically nondecreasing clock. Similar to
/// [`std::time::Instant`](std::time::Instant) but is faster and more
/// accurate if TSC is available.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct Instant(u64);
impl Instant {
/// A default `Instant` that can be seen as a fixed but random moment.
pub const ZERO: Instant = Instant(0);
#[inline]
/// Returns an instant corresponding to "now".
///
/// # Examples
///
/// ```
/// use minstant::Instant;
///
/// let now = Instant::now();
/// ```
pub fn now() -> Instant {
Instant(crate::current_cycle())
}
/// Returns the amount of time elapsed from another instant to this one,
/// or zero duration if that instant is later than this one.
///
/// # Panics
///
/// Previously we panicked if `earlier` was later than `self`. Currently this method saturates
/// to follow the behavior of the standard library. Future versions may reintroduce the panic
/// in some circumstances.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use std::thread::sleep;
///
/// use minstant::Instant;
///
/// let now = Instant::now();
/// sleep(Duration::new(1, 0));
/// let new_now = Instant::now();
/// println!("{:?}", new_now.duration_since(now));
/// println!("{:?}", now.duration_since(new_now)); // 0ns
/// ```
pub fn duration_since(&self, earlier: Instant) -> Duration {
self.checked_duration_since(earlier).unwrap_or_default()
}
/// Returns the amount of time elapsed from another instant to this one,
/// or None if that instant is later than this one.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use std::thread::sleep;
///
/// use minstant::Instant;
///
/// let now = Instant::now();
/// sleep(Duration::new(1, 0));
/// let new_now = Instant::now();
/// println!("{:?}", new_now.checked_duration_since(now));
/// println!("{:?}", now.checked_duration_since(new_now)); // None
/// ```
pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
Some(Duration::from_nanos(
(self.0.checked_sub(earlier.0)? as f64 * crate::nanos_per_cycle()) as u64,
))
}
/// Returns the amount of time elapsed from another instant to this one,
/// or zero duration if that instant is later than this one.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use std::thread::sleep;
///
/// use minstant::Instant;
///
/// let now = Instant::now();
/// sleep(Duration::new(1, 0));
/// let new_now = Instant::now();
/// println!("{:?}", new_now.saturating_duration_since(now));
/// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
/// ```
pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
self.checked_duration_since(earlier).unwrap_or_default()
}
/// Returns the amount of time elapsed since this instant was created.
///
/// # Panics
///
/// This function may panic if the current time is earlier than this
/// instant, which is something that can happen if an `Instant` is
/// produced synthetically.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use std::thread::sleep;
///
/// use minstant::Instant;
///
/// let instant = Instant::now();
/// let three_secs = Duration::from_secs(3);
/// sleep(three_secs);
/// assert!(instant.elapsed() >= three_secs);
/// ```
#[inline]
pub fn elapsed(&self) -> Duration {
Instant::now() - *self
}
/// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
/// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
/// otherwise.
pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
self.0
.checked_add((duration.as_nanos() as u64 as f64 / crate::nanos_per_cycle()) as u64)
.map(Instant)
}
/// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
/// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
/// otherwise.
pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
self.0
.checked_sub((duration.as_nanos() as u64 as f64 / crate::nanos_per_cycle()) as u64)
.map(Instant)
}
/// Convert interal clocking counter into a UNIX timestamp represented as the
/// nanoseconds elapsed from [UNIX_EPOCH](std::time::UNIX_EPOCH).
///
/// [`Anchor`](crate::Anchor) contains the necessary calibration data for conversion.
/// Typically, initializing an [`Anchor`](crate::Anchor) takes about 50 nano seconds, so
/// try to reuse it for a batch of `Instant`.
///
/// # Examples
///
/// ```
/// use std::time::UNIX_EPOCH;
/// use minstant::{Instant, Anchor};
///
/// let anchor = Anchor::new();
/// let instant = Instant::now();
///
/// let expected = UNIX_EPOCH.elapsed().unwrap().as_nanos();
/// assert!((instant.as_unix_nanos(&anchor) as i64 - expected as i64).abs() < 1_000_000);
/// ```
pub fn as_unix_nanos(&self, anchor: &Anchor) -> u64 {
if self.0 > anchor.cycle {
let forward_ns = ((self.0 - anchor.cycle) as f64 * crate::nanos_per_cycle()) as u64;
anchor.unix_time_ns + forward_ns
} else {
let backward_ns = ((anchor.cycle - self.0) as f64 * crate::nanos_per_cycle()) as u64;
anchor.unix_time_ns - backward_ns
}
}
}
impl Add<Duration> for Instant {
type Output = Instant;
fn add(self, other: Duration) -> Instant {
self.checked_add(other)
.expect("overflow when adding duration to instant")
}
}
impl AddAssign<Duration> for Instant {
fn add_assign(&mut self, other: Duration) {
*self = *self + other;
}
}
impl Sub<Duration> for Instant {
type Output = Instant;
fn sub(self, other: Duration) -> Instant {
self.checked_sub(other)
.expect("overflow when subtracting duration from instant")
}
}
impl SubAssign<Duration> for Instant {
fn sub_assign(&mut self, other: Duration) {
*self = *self - other;
}
}
impl Sub<Instant> for Instant {
type Output = Duration;
/// Returns the amount of time elapsed from another instant to this one,
/// or zero duration if that instant is later than this one.
///
/// # Panics
///
/// Previously we panicked if `other` was later than `self`. Currently this method saturates
/// to follow the behavior of the standard library. Future versions may reintroduce the panic
/// in some circumstances.
fn sub(self, other: Instant) -> Duration {
self.duration_since(other)
}
}
impl std::fmt::Debug for Instant {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
/// An anchor which can be used to convert internal clocking counter into system timestamp.
///
/// *[See also the `Instant::as_unix_nanos()`](crate::Instant::as_unix_nanos).*
#[derive(Copy, Clone)]
pub struct Anchor {
unix_time_ns: u64,
cycle: u64,
}
impl Default for Anchor {
fn default() -> Self {
Self::new()
}
}
impl Anchor {
#[inline]
pub fn new() -> Anchor {
let unix_time_ns = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("unexpected time drift")
.as_nanos() as u64;
Anchor {
unix_time_ns,
cycle: crate::current_cycle(),
}
}
}
#[cfg(all(feature = "atomic", target_has_atomic = "64"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "atomic", target_has_atomic = "64"))))]
mod atomic {
use super::Instant;
use std::sync::atomic::{AtomicU64, Ordering};
#[cfg(doc)]
use Ordering::*;
/// Atomic variant of [`Instant`].
#[derive(Debug)]
#[repr(transparent)]
pub struct Atomic(AtomicU64);
impl Atomic {
/// Maximum with the current value.
///
/// Finds the maximum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
/// `[u64]`.
#[inline]
pub fn fetch_max(&self, val: Instant, order: Ordering) -> Instant {
Instant(self.0.fetch_max(val.0, order))
}
/// Minimum with the current value.
///
/// Finds the minimum of the current value and the argument `val`, and
/// sets the new value to the result.
///
/// Returns the previous value.
///
/// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
/// `[u64]`.
#[inline]
pub fn fetch_min(&self, val: Instant, order: Ordering) -> Instant {
Instant(self.0.fetch_min(val.0, order))
}
/// Consumes the atomic and returns the contained [`Instant`].
///
/// This is safe because passing `self` by value guarantees that no other threads are
/// concurrently accessing the atomic data.
#[inline]
pub fn into_instant(self) -> Instant {
Instant(self.0.into_inner())
}
/// Loads a value from the [`Atomic`].
///
/// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Release`] or [`AcqRel`].
#[inline]
pub fn load(&self, order: Ordering) -> Instant {
Instant(self.0.load(order))
}
/// Creates a new [`Atomic`].
#[inline]
pub fn new(v: Instant) -> Self {
Self(AtomicU64::new(v.0))
}
/// Stores a value into the [`Atomic`].
///
/// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
/// Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
///
/// # Panics
///
/// Panics if `order` is [`Acquire`] or [`AcqRel`].
#[inline]
pub fn store(&self, val: Instant, order: Ordering) {
self.0.store(val.0, order)
}
/// Stores a value into the [`Atomic`], returning the previous value.
///
/// `swap` takes an [`Ordering`] argument which describes the memory ordering
/// of this operation. All ordering modes are possible. Note that using
/// [`Acquire`] makes the store part of this operation [`Relaxed`], and
/// using [`Release`] makes the load part [`Relaxed`].
///
/// **Note**: This method is only available on platforms that support atomic operations on
/// `u64`
#[inline]
pub fn swap(&self, val: Instant, order: Ordering) -> Instant {
Instant(self.0.swap(val.0, order))
}
}
impl From<Instant> for Atomic {
#[inline]
fn from(instant: Instant) -> Self {
Self::new(instant)
}
}
}
#[cfg(all(feature = "atomic", target_has_atomic = "64"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "atomic", target_has_atomic = "64"))))]
pub use atomic::Atomic;