qubit-clock

Thread-safe clock abstractions for Rust: monotonic clocks, mock testing, high-precision time meters, and timezone support

Rust CI Coverage Crates.io Rust License

Thread-safe clock and sleep abstractions for Rust with monotonic and mock implementations.

Overview

Qubit Clock provides a flexible and type-safe clock abstraction system for Rust applications. It offers robust, thread-safe clock implementations with support for basic time access, high-precision measurements, timezone handling, monotonic time, mockable relative sleeps, and testing support.

Features

πŸ• Clock Abstractions

⏰ Clock Implementations

⏱️ Time Meters

⏲️ Sleep Abstractions

πŸ”’ Thread Safety

🌍 Timezone Support

πŸ§ͺ Testing Support

Installation

Add this to your Cargo.toml:

[dependencies]
qubit-clock = "0.8"

Quick Start

Basic Usage

use qubit_clock::{Clock, SystemClock};

let clock = SystemClock::new();
let timestamp = clock.millis();
let time = clock.time();
println!("Current time: {}", time);

With Timezone

use qubit_clock::{Clock, ZonedClock, SystemClock, Zoned};
use chrono_tz::Asia::Shanghai;

let clock = Zoned::new(SystemClock::new(), Shanghai);
let local = clock.local_time();
println!("Local time in Shanghai: {}", local);

Monotonic Time for Performance Measurement

use qubit_clock::{Clock, MonotonicClock};
use std::thread;
use std::time::Duration;

let clock = MonotonicClock::new();
let start = clock.millis();

thread::sleep(Duration::from_millis(100));

let elapsed = clock.millis() - start;
println!("Elapsed: {} ms", elapsed);

Testing with MockClock

use qubit_clock::{Clock, ControllableClock, MockClock};
use chrono::{DateTime, Duration, Utc};

let clock = MockClock::new();

// Set to a specific time
let fixed_time = DateTime::parse_from_rfc3339(
    "2024-01-01T00:00:00Z"
).unwrap().with_timezone(&Utc);
clock.set_time(fixed_time);

assert_eq!(clock.time(), fixed_time);

// Advance time
clock.add_duration(Duration::hours(1));
assert_eq!(clock.time(), fixed_time + Duration::hours(1));

High-Precision Measurements

use qubit_clock::{NanoClock, NanoMonotonicClock};

let clock = NanoMonotonicClock::new();
let start = clock.nanos();

// Perform some operation
for _ in 0..1000 {
    // Some work
}

let elapsed = clock.nanos() - start;
println!("Elapsed: {} ns", elapsed);

Time Meters for Elapsed Time Measurement

use qubit_clock::meter::TimeMeter;
use std::thread;
use std::time::Duration;

let mut meter = TimeMeter::new();
meter.start();
thread::sleep(Duration::from_millis(100));
meter.stop();
println!("Elapsed: {}", meter.readable_duration());

Unified Mock Time for Tests

use qubit_clock::{Clock, MockTime};
use qubit_clock::sleep::Sleeper;
use std::time::Duration;

let mock = MockTime::unix_epoch();
let clock = mock.clock();
let sleeper = mock.sleeper();
let worker = sleeper.clone();
let handle = std::thread::spawn(move || {
    worker.sleep_for(Duration::from_secs(5));
});

assert!(mock.timeline().wait_for_blocked_waiters(
    qubit_clock::MockWaiterKind::Sleep,
    1,
    Duration::from_secs(1),
));
mock.advance(Duration::from_secs(5));
handle.join().expect("mock sleep should finish");
assert_eq!(clock.millis(), 5_000);

High-Precision Time Meter

use qubit_clock::meter::NanoTimeMeter;

let mut meter = NanoTimeMeter::new();
meter.start();

// Perform some operation
for _ in 0..1000 {
    // Some work
}

meter.stop();
println!("Elapsed: {} ns", meter.nanos());
println!("Readable: {}", meter.readable_duration());

Speed Calculation with Time Meter

use qubit_clock::meter::TimeMeter;
use std::thread;
use std::time::Duration;

let mut meter = TimeMeter::new();
meter.start();

// Process 1000 items
for _ in 0..1000 {
    thread::sleep(Duration::from_micros(100));
}

meter.stop();
println!("Processed 1000 items in {}", meter.readable_duration());
println!("Speed: {}", meter.formatted_speed_per_second(1000));

Architecture

The crate is built around several orthogonal traits:

This design follows the Interface Segregation Principle, ensuring that implementations only need to provide the features they actually support.

Clock Implementations

SystemClock

MonotonicClock

NanoMonotonicClock

MockClock

MockTimeline

MockTime

Zoned\<C\>

Sleep Implementations

SystemSleeper

MockSleeper

Time Meters

TimeMeter

A millisecond-precision time meter for measuring elapsed time with the following features:

Example output formats:

NanoTimeMeter

A nanosecond-precision time meter with features similar to TimeMeter:

Example output formats:

Why Not Just Use std::time::Instant?

std::time::Instant is the right primitive for measuring real elapsed time in production code. It is monotonic, fast, and simple:

let start = std::time::Instant::now();
// do work
let elapsed = start.elapsed();

This crate exists for the cases where elapsed-time measurement is only part of the problem:

In short, Instant measures real elapsed time; mock clocks make time controllable for tests; time meters turn elapsed-time measurement into a reusable, formatted, testable abstraction.

API Reference

Clock Trait

The core Clock trait provides:

NanoClock Trait

Extension trait for high-precision clocks:

ZonedClock Trait

Extension trait for timezone support:

Use Zoned::new(clock, tz) to select the timezone for a clock.

ControllableClock Trait

Extension trait for controllable clocks (testing):

Mock Time Runtime

Mock time APIs are available at the crate root:

Sleep Traits

Sleep APIs are available under qubit_clock::sleep:

Sleep APIs intentionally model only relative sleeping. Notification waits, condition waits, and timeout waits belong to monitor primitives in qubit-lock.

Design Principles

Interface Segregation

The crate follows the Interface Segregation Principle by providing separate traits for different capabilities:

This allows implementations to provide only the features they need, keeping the API clean and focused.

Single Responsibility

Each trait and type has one clear purpose:

Composition over Inheritance

Functionality is extended through wrappers rather than inheritance:

Zero-Cost Abstractions

The design ensures you only pay for what you use:

Testing & Code Coverage

This project maintains comprehensive test coverage with detailed validation of all functionality.

Running Tests

# Run all tests
cargo test

# Run with coverage report
./coverage.sh

# Generate text format report
./coverage.sh text

# Run CI checks (tests, lints, formatting)
./ci-check.sh

Dependencies

Use Cases

Performance Monitoring

use qubit_clock::meter::TimeMeter;

let mut meter = TimeMeter::new();
meter.start();

// Perform operation
process_data();

meter.stop();
log::info!("Processing took: {}", meter.readable_duration());

Mockable Sleep Control

use qubit_clock::MockTime;
use qubit_clock::sleep::Sleeper;
use std::time::Duration;

fn retry_once<S: Sleeper>(sleeper: &S) {
    sleeper.sleep_for(Duration::from_millis(10));
}

let mock = MockTime::unix_epoch();
let sleeper = mock.sleeper();
let worker = sleeper.clone();
let handle = std::thread::spawn(move || retry_once(&worker));

assert!(mock.timeline().wait_for_blocked_waiters(
    qubit_clock::MockWaiterKind::Sleep,
    1,
    Duration::from_secs(1),
));
mock.advance(Duration::from_millis(10));
handle.join().expect("retry should finish");

Testing Time-Dependent Logic

use qubit_clock::{Clock, ControllableClock, MockClock};
use chrono::Duration;

#[test]
fn test_expiration() {
    let clock = MockClock::new();
    let item = Item::new(clock.clone());

    // Fast-forward 1 hour
    clock.add_duration(Duration::hours(1));

    assert!(item.is_expired());
}

Benchmarking

use qubit_clock::meter::NanoTimeMeter;

let mut meter = NanoTimeMeter::new();
meter.start();

for _ in 0..10000 {
    expensive_operation();
}

meter.stop();
println!("Average time per operation: {} ns", meter.nanos() / 10000);

License

Copyright (c) 2025 - 2026. Haixing Hu.

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.

See LICENSE for the full license text.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Author

Haixing Hu - Qubit Co. Ltd.

---

For more information about the Qubit open source projects, visit our GitHub homepage.