Skip to main content

MonotonicClock

Struct MonotonicClock 

Source
pub struct MonotonicClock<const N: u64 = 1> { /* private fields */ }
Available on target_has_atomic=64 and crate feature alloc and crate feature std only.
Expand description

A monotonic time source that returns elapsed time since process start, offset from a user-defined epoch.

This avoids wall-clock adjustments (e.g., NTP or daylight savings changes) while still aligning timestamps to a fixed origin.

Internally, the clock measures time by capturing Instant::now() at construction and adding to it the duration elapsed since a given epoch (computed from SystemTime::now() at startup).

N controls the number of real milliseconds represented by one returned time unit. MonotonicClock and MonotonicClock<1> return literal milliseconds, while MonotonicClock<8> returns 8-millisecond ticks.

use ferroid::time::{MonotonicClock, UNIX_EPOCH};

let _ = MonotonicClock::<0>::with_epoch(UNIX_EPOCH);

Implementations§

Source§

impl<const N: u64> MonotonicClock<N>

Source

pub const GRANULARITY_MILLIS: u64 = N

Source

pub fn with_epoch(epoch: Duration) -> Self

Constructs a monotonic clock using a custom epoch as the origin (t = 0), specified in milliseconds since the Unix epoch.

The provided epoch defines the zero-point for all future timestamps returned by this clock. Internally, the clock uses a shared background thread that updates a global atomic counter once per millisecond, using a monotonic timer (Instant) to measure elapsed time since startup.

Different epochs are supported by applying a per-instance offset to the shared ticker value.

On each call to current_millis, the clock returns the current tick value plus a fixed offset - the precomputed difference between the current wall-clock time (SystemTime::now()) and the given epoch. The final value is quantized into N-millisecond units.

This design avoids syscalls on the hot path and ensures that time never goes backward, even if the system clock is adjusted externally.

§Parameters
  • epoch: The origin timestamp, as a Duration since 1970-01-01 UTC.
§Example
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use ferroid::time::{MonotonicClock, TimeSource};
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
// Or use a default epoch
// use ferroid::TWITTER_EPOCH,
// let now = TWITTER_EPOCH;

let clock = MonotonicClock::<1>::with_epoch(now);

std::thread::sleep(Duration::from_millis(5));

let ts: u64 = clock.current_millis();

// On most systems, this will report a value near 5 ms. However, due to
// small differences in timer alignment and sleep accuracy, the counter
// may be slightly behind or ahead on the first read. It's common to
// observe values like 4–6 ms after sleeping for 5 ms. The value will
// never go backward and is guaranteed to increase monotonically.
// assert!(ts >= ~5);

This allows you to control the timestamp layout by anchoring all generated times to a custom epoch of your choosing.

Trait Implementations§

Source§

impl<const N: u64> Clone for MonotonicClock<N>

Source§

fn clone(&self) -> MonotonicClock<N>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<const N: u64> Debug for MonotonicClock<N>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for MonotonicClock<1>

Source§

fn default() -> Self

Constructs a monotonic clock aligned to the default UNIX_EPOCH.

Source§

impl<const N: u64> TimeSource<u64> for MonotonicClock<N>

Source§

fn current_millis(&self) -> u64

Returns the number of N-millisecond units since the configured epoch, based on the elapsed monotonic time since construction.

Source§

const GRANULARITY_MILLIS: u64 = Self::GRANULARITY_MILLIS

The number of real milliseconds represented by one returned time unit.
Source§

impl<const N: u64> TimeSource<u128> for MonotonicClock<N>

Source§

fn current_millis(&self) -> u128

Returns the number of N-millisecond units since the configured epoch, based on the elapsed monotonic time since construction.

Source§

const GRANULARITY_MILLIS: u64 = Self::GRANULARITY_MILLIS

The number of real milliseconds represented by one returned time unit.

Auto Trait Implementations§

§

impl<const N: u64 = 1> !RefUnwindSafe for MonotonicClock<N>

§

impl<const N: u64 = 1> !UnwindSafe for MonotonicClock<N>

§

impl<const N: u64> Freeze for MonotonicClock<N>

§

impl<const N: u64> Send for MonotonicClock<N>

§

impl<const N: u64> Sync for MonotonicClock<N>

§

impl<const N: u64> Unpin for MonotonicClock<N>

§

impl<const N: u64> UnsafeUnpin for MonotonicClock<N>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.