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};


/// CPU Time Used by The Whole Process
///
/// This is an opaque type similar to `std::time::Instant`.
/// Use `elapsed()` or `duration_since()` to get meaningful time deltas.
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub struct ProcessTime(Duration);

/// CPU Time Used by The Current Thread
///
/// This is an opaque type similar to `std::time::Instant`.
/// Use `elapsed()` or `duration_since()` to get meaningful time deltas.
///
/// This type is non-thread-shareable (!Sync, !Send) because otherwise it's
/// to easy to mess up times from different threads. However, you can freely
/// send Duration's returned by `elapsed()` and `duration_since()`.
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub struct ThreadTime(Duration,
                      // makes type non-sync and non-send
                      PhantomData<Rc<()>>);


impl ProcessTime {
    /// Get current CPU time used by a process process
    ///
    /// # Panics
    ///
    /// This method panics if linux kernel doesn't support
    /// CLOCK_PROCESS_CPUTIME_ID, which works since linux 2.6.12 (~ year 2005).
    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))
    }
    /// Returns the amount of CPU time used from the previous timestamp to now.
    pub fn elapsed(&self) -> Duration {
        ProcessTime::now().duration_since(*self)
    }
    /// Returns the amount of CPU time used from the previous timestamp.
    pub fn duration_since(&self, timestamp: ProcessTime) -> Duration {
        self.0 - timestamp.0
    }
}

impl ThreadTime {
    /// Get current CPU time used by a process process
    ///
    /// # Panics
    ///
    /// This method panics if linux kernel doesn't support
    /// CLOCK_THREAD_CPUTIME_ID, which works since linux 2.6.12 (~ year 2005).
    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)
    }
    /// Returns the amount of CPU time used by the current thread
    /// from the previous timestamp to now.
    pub fn elapsed(&self) -> Duration {
        ThreadTime::now().duration_since(*self)
    }
    /// Returns the amount of CPU time used by the current thread
    /// from the previous timestamp.
    pub fn duration_since(&self, timestamp: ThreadTime) -> Duration {
        self.0 - timestamp.0
    }
}