use libc::{
clock_gettime, clockid_t, timespec, CLOCK_MONOTONIC, CLOCK_PROCESS_CPUTIME_ID, CLOCK_REALTIME,
CLOCK_THREAD_CPUTIME_ID,
};
use std::io::Error;
use std::time::Duration;
use crate::Clock;
pub struct PosixClock(clockid_t);
impl PosixClock {
pub unsafe fn from_clockid(clockid: clockid_t) -> PosixClock {
PosixClock(clockid)
}
}
pub const REALTIME_CLOCK: PosixClock = PosixClock(CLOCK_REALTIME);
pub const MONOTONIC_CLOCK: PosixClock = PosixClock(CLOCK_MONOTONIC);
pub const PROCESS_CLOCK: PosixClock = PosixClock(CLOCK_PROCESS_CPUTIME_ID);
const CURRENT_THREAD_CPUTIME_CLOCK: PosixClock = PosixClock(CLOCK_THREAD_CPUTIME_ID);
pub fn get_current_thread_cpu_time() -> Result<Duration, Error> {
CURRENT_THREAD_CPUTIME_CLOCK.get_time()
}
impl Clock for PosixClock {
fn get_time(&self) -> Result<Duration, Error> {
let mut timespec = timespec {
tv_sec: 0,
tv_nsec: 0,
};
let s = unsafe { clock_gettime(self.0, &mut timespec) };
if s == -1 {
return Err(Error::last_os_error());
}
Ok(Duration::new(
timespec.tv_sec as u64, timespec.tv_nsec as u32, ))
}
}