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

#866 in Operating systems

Download history 6/week @ 2024-11-13 8/week @ 2024-11-20 23/week @ 2024-11-27 76/week @ 2024-12-04 135/week @ 2024-12-11 22/week @ 2024-12-18 14/week @ 2025-01-01 34/week @ 2025-01-08 97/week @ 2025-01-15 153/week @ 2025-01-22 240/week @ 2025-01-29 91/week @ 2025-02-05 157/week @ 2025-02-12 128/week @ 2025-02-19 41/week @ 2025-02-26

468 downloads per month
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–2MB
~38K SLoC