5 unstable releases

0.3.1 Sep 11, 2020
0.3.0 Sep 11, 2020
0.2.1 Sep 11, 2020
0.2.0 Sep 10, 2020
0.1.0 Sep 10, 2020

#542 in Operating systems


Used in timeouts

MIT license

16KB
233 lines

os_clock

Access various operating system clocks (such as per-thread CPU Time, system clock, monotomic, etc) on Unix-family systems.

use os_clock::{self, Clock};

let clock = cpu_clock_for_current_thread();
clock.get_time();

Notably, a clock for the CPU time of one thread can be accessed from another thread:

let clock = cpu_clock_for_current_thread().unwrap();

loop {
    if clock.get_time().unwrap() > Duration::from_millis(5) {
        break;
    }
}

std::thread::spawn(move || {
    assert!(clock.get_time().unwrap() > Duration::from_millis(5));

    let self_clock = cpu_clock_for_current_thread().unwrap();
    assert!(self_clock.get_time().unwrap() < Duration::from_millis(1));
})
.join()
.unwrap();

Compatibility

Works on recent iOS, Mac, as well as Unix-family systems with a pthread.h that defines pthread_getcpuclockid (most modern Linux).


lib.rs:

Access various operating system clocks (such as per-thread CPU Time, system clock, monotomic, etc) on Unix-family systems.

Thread clocks:

Sendable per-thread CPU clocks are unique to this crate:

#
let clock = os_clock::cpu_clock_for_current_thread().unwrap();

let start_time = clock.get_time().unwrap();
// Do some work for 5ms...
assert!(clock.get_time().unwrap() > start_time + Duration::from_millis(5));

// Notably, a clock for the CPU time of one thread can be accessed from another thread:
std::thread::spawn(move || {
    assert!(clock.get_time().unwrap() > Duration::from_millis(5));

    let self_clock = os_clock::cpu_clock_for_current_thread().unwrap();
    assert!(self_clock.get_time().unwrap() < Duration::from_millis(1));
})
.join()

// Clocks count from the thread's spawn time
let new_clock = os_clock::cpu_clock_for_current_thread().unwrap();
assert!(new_clock.get_time().unwrap() > Duration::from_millis(5));

// Use a timer to start counting from the moment the timer is created
let timer = new_clock.start_timer().unwrap();
assert!(timer.elapsed().unwrap() < Duration::from_millis(1));
// Do some work for 5ms...
assert!(timer.elapsed().unwrap() > Duration::from_millis(5));

Dependencies

~0–1.8MB
~35K SLoC