1use std::os::raw::c_int;
4use std::ptr::null_mut;
5use std::time::{Duration, Instant, SystemTime};
6
7#[repr(C)]
8#[derive(Clone)]
9struct Timeval {
10 pub tv_sec: i64,
11 pub tv_usec: i64,
12}
13
14#[repr(C)]
15#[derive(Clone)]
16struct Itimerval {
17 pub it_interval: Timeval,
18 pub it_value: Timeval,
19}
20
21extern "C" {
22 fn setitimer(which: c_int, new_value: *mut Itimerval, old_value: *mut Itimerval) -> c_int;
23}
24
25const ITIMER_PROF: c_int = 2;
26
27pub struct Timer {
28 pub frequency: c_int,
29 pub start_time: SystemTime,
30 pub start_instant: Instant,
31}
32
33impl Timer {
34 pub fn new(frequency: c_int) -> Timer {
35 let interval = 1e6 as i64 / i64::from(frequency);
36 let it_interval = Timeval {
37 tv_sec: interval / 1e6 as i64,
38 tv_usec: interval % 1e6 as i64,
39 };
40 let it_value = it_interval.clone();
41
42 unsafe {
43 setitimer(
44 ITIMER_PROF,
45 &mut Itimerval {
46 it_interval,
47 it_value,
48 },
49 null_mut(),
50 )
51 };
52
53 Timer {
54 frequency,
55 start_time: SystemTime::now(),
56 start_instant: Instant::now(),
57 }
58 }
59
60 pub fn timing(&self) -> ReportTiming {
63 ReportTiming {
64 frequency: self.frequency,
65 start_time: self.start_time,
66 duration: self.start_instant.elapsed(),
67 }
68 }
69}
70
71impl Drop for Timer {
72 fn drop(&mut self) {
73 let it_interval = Timeval {
74 tv_sec: 0,
75 tv_usec: 0,
76 };
77 let it_value = it_interval.clone();
78 unsafe {
79 setitimer(
80 ITIMER_PROF,
81 &mut Itimerval {
82 it_interval,
83 it_value,
84 },
85 null_mut(),
86 )
87 };
88 }
89}
90
91#[derive(Clone)]
93pub struct ReportTiming {
94 pub frequency: i32,
96 pub start_time: SystemTime,
98 pub duration: Duration,
100}
101
102impl Default for ReportTiming {
103 fn default() -> Self {
104 Self {
105 frequency: 1,
106 start_time: SystemTime::UNIX_EPOCH,
107 duration: Default::default(),
108 }
109 }
110}