use std::time::Duration;
use std::rc::Rc;
use std::marker::PhantomData;
use libc::{clock_gettime, timespec};
use libc::{CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID};
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub struct ProcessTime(Duration);
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub struct ThreadTime(Duration,
PhantomData<Rc<()>>);
impl ProcessTime {
pub fn now() -> ProcessTime {
let mut time = timespec {
tv_sec: 0,
tv_nsec: 0,
};
if unsafe { clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &mut time) } == -1
{
panic!("Process CPU time is not supported");
}
ProcessTime(Duration::new(time.tv_sec as u64, time.tv_nsec as u32))
}
pub fn elapsed(&self) -> Duration {
ProcessTime::now().duration_since(*self)
}
pub fn duration_since(&self, timestamp: ProcessTime) -> Duration {
self.0 - timestamp.0
}
}
impl ThreadTime {
pub fn now() -> ThreadTime {
let mut time = timespec {
tv_sec: 0,
tv_nsec: 0,
};
if unsafe { clock_gettime(CLOCK_THREAD_CPUTIME_ID, &mut time) } == -1
{
panic!("Process CPU time is not supported");
}
ThreadTime(Duration::new(time.tv_sec as u64, time.tv_nsec as u32),
PhantomData)
}
pub fn elapsed(&self) -> Duration {
ThreadTime::now().duration_since(*self)
}
pub fn duration_since(&self, timestamp: ThreadTime) -> Duration {
self.0 - timestamp.0
}
}