1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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
}
}