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
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
pub use std::collections::HashMap;
pub use global::Global;
pub use cpu_time::ProcessTime;
use std::hash::Hash;

/// Structure used to keep track of the current process time since the last `start_timer!()` call,
/// as well as the sum of all previously calculated times.
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct TimerState {
    process_time: ProcessTime,
    total_ns: u128
}

impl TimerState {
    pub fn new() -> Self {
        TimerState {
            process_time: ProcessTime::now(),
            total_ns: 0
        }
    }

    /// Helper function to add time up to a certain ProcessTime
    pub fn add_time(&mut self, up_to: ProcessTime){
        self.total_ns += up_to.duration_since(self.process_time).as_nanos();
    }

    /// Setter function to reset time to the given ProcessTime
    pub fn reset_time(&mut self, new_time: ProcessTime){
        self.process_time = new_time;
    }

    /// Getter function to the total_ns variable
    pub fn get_total_elapsed_ns(&self) -> u128 {
        self.total_ns
    }
}

/// Prepares the global variable `TIMERS`. Must be called before any other macro from this crate,
/// or the other calls will panic
#[macro_export]
macro_rules! prepare_timer {
    () => {
            #[cfg(feature="breezy_timer")]
            static TIMERS: $crate::Global<std::collections::HashMap<&'static str, $crate::TimerState>> = $crate::Global::new();
    }
}

/// Creates or updates a timer with the provided name. The same timer can be started and stopped
/// as many times as needed, and will keep track of the sum of all the time spent
#[macro_export]
macro_rules! start_timer {
    ( $x:expr ) => {
        #[cfg(feature="breezy_timer")]
        {
            TIMERS.with_mut(|hashmap| {
                hashmap.entry($x)
                    .and_modify(|entry| entry.reset_time($crate::ProcessTime::now()))
                    .or_insert($crate::TimerState::new());
            });
        }
    };
}

/// Stops the timer with the provided name. The timer must already exist, or this call will panic.
/// The same timer can be started and stopped as many times as needed, and will keep track of the
/// sum of all the time spent
#[macro_export]
macro_rules! stop_timer {
    ( $x:expr ) => {
        #[cfg(feature="breezy_timer")]
        {
            let before = cpu_time::ProcessTime::now();
            TIMERS.with_mut(|hashmap| {
                let entry = hashmap.get_mut($x).unwrap();
                entry.add_time(before);
            });
        }
    };
}

/// Returns the amount of nanoseconds elapsed by the timer with the provided name. If feature
/// `breezy_timer` is not active, returns 0 (to avoid breaking code which depends on the output)
#[macro_export]
macro_rules! elapsed_ns {
    ( $x:expr) => {
        {
            #[cfg(feature="breezy_timer")]
            {
                TIMERS.with(|hashmap| hashmap[$x].get_total_elapsed_ns())
            }

            #[cfg(not(feature="breezy_timer"))]
            {
                0u128
            }
        }
    }
}

/// Helper function to clone a hashmap, needed by the macro `get_timers_map!()`
pub fn clone_hashmap<A: Clone+Eq+Hash, B: Clone+Eq>(hashmap: &HashMap<A, B>) -> HashMap<A, B> {
    let mut new_hashmap = HashMap::new();
    for (a,b) in hashmap.iter(){
        new_hashmap.insert(a.clone(), b.clone());
    }
    new_hashmap
}

/// Returns the hashmap containing each timer. The key corresponds to the timer name, and the value
/// is an instance of `TimerState`. If feature `breezy_timer` is not active, return an empty
/// `HashMap` (to avoid breaking code which depends on the output)
#[macro_export]
macro_rules! get_timers_map {
    () => {
        {
            #[cfg(feature="breezy_timer")]
            {
                TIMERS.with(|hashmap| $crate::clone_hashmap(hashmap))
            }
            #[cfg(not(feature="breezy_timer"))]
            {
                use std::collections::HashMap;
                HashMap::<&'static str, $crate::TimerState>::new()
            }
        }
    }
}

#[cfg(all(test, feature="breezy_timer"))]
mod tests {
    use cpu_time::ProcessTime;
    use criterion::black_box;

    #[test]
    fn check() {
        prepare_timer!();

        let start = ProcessTime::now();
        start_timer!("loop");
        assert!(TIMERS.lock().unwrap().contains_key("loop"));
        let mut total = 0;
        for _ in 0..100 {
            total += black_box(1);
        }
        black_box(total);
        stop_timer!("loop");
        let elapsed_ns = start.elapsed().as_nanos();

        let elapsed_macro = elapsed_ns!("loop");
        assert!(elapsed_macro > 0);
        assert!(elapsed_macro < elapsed_ns);
    }

    #[test]
    fn sanity_check(){
        let mut vectors = Vec::new();

        prepare_timer!();
        start_timer!("total");
        for _ in 0..10 {
            start_timer!("allocations");
            let vec: Vec<u8> = (0..102400).map(|_| { rand::random::<u8>() }).collect();
            vectors.push(vec);
            stop_timer!("allocations");

            start_timer!("sum");
            let mut total = 0;
            for v in vectors.iter() {
                total += v.iter().map(|x| *x as u32).sum::<u32>();
            }
            // used so that compiler doesn't simply remove the loop because nothing is done with total
            black_box(total);
            stop_timer!("sum");
        }
        stop_timer!("total");
        assert!(elapsed_ns!("allocations") < elapsed_ns!("total"));
        assert!(elapsed_ns!("sum") < elapsed_ns!("total"))
    }
}

#[cfg(all(test, not(feature="breezy_timer")))]
mod tests {
    use cpu_time::ProcessTime;
    use criterion::black_box;

    #[test]
    fn check_no_feature() {
        prepare_timer!();

        let start = ProcessTime::now();
        start_timer!("loop");
        let mut total = 0;
        for _ in 0..100 {
            total += black_box(1);
        }
        stop_timer!("loop");
        let elapsed_ns = start.elapsed().as_nanos();
        let elapsed_macro = elapsed_ns!("loop");
        assert!(elapsed_macro == 0);
    }
}