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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/*<LICENSE>
    This file is part of Memthol.

    Copyright (C) 2020 OCamlPro.

    Memthol is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Memthol is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Memthol.  If not, see <https://www.gnu.org/licenses/>.
*/

//! Stopwatch, for time statistics.

use std::fmt;

use std::time::{Duration, Instant};

/// Stopwatch.
#[derive(Debug, Clone)]
pub struct RealStopwatch {
    /// Remember the time counted before the last start, if any.
    elapsed: Duration,
    /// Instant of the last start order not followed by a stop order.
    last_start: Option<Instant>,
}

impl fmt::Display for RealStopwatch {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        let elapsed = self.elapsed();
        let (secs, subsec_nanos) = (elapsed.as_secs(), elapsed.subsec_nanos());
        if subsec_nanos == 0 {
            write!(fmt, "{}s", secs)
        } else {
            write!(fmt, "{}.{:0>9}s", secs, subsec_nanos)
        }
    }
}

/// Stopwatch.
#[derive(Debug, Clone)]
pub struct FakeStopwatch;

impl fmt::Display for FakeStopwatch {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        "???".fmt(fmt)
    }
}

macro_rules! fn_defs {
    ($(
        $(#[$fn_meta:meta])*
        $fn_vis:vis fn $fn_id:ident
            $(<$($t_params:ident),* $(,)?>)?
            ( $($fn_args:tt)* ) $(-> $fn_out:ty)?
        {
            $($profiling_def:tt)*
        } {
            $($not_profiling_def:tt)*
        }
    )*) => {
        impl RealStopwatch {
            /// True if we are profiling.
            pub const TIME_STATS_ACTIVE: bool = true;
            $(
                $(#[$fn_meta])*
                #[inline]
                $fn_vis fn $fn_id $(<$($t_params),*>)? ($($fn_args)*) $(-> $fn_out)? {
                    $($profiling_def)*
                }
            )*
        }

        impl FakeStopwatch {
            /// True if we are profiling.
            pub const TIME_STATS_ACTIVE: bool = false;
            $(
                $(#[$fn_meta])*
                #[inline]
                $fn_vis fn $fn_id $(<$($t_params),*>)? ($($fn_args)*) $(-> $fn_out)? {
                    $($not_profiling_def)*
                }
            )*
        }
    }
}

impl RealStopwatch {
    /// Applies an action to the time counted so far.
    pub fn elapsed(&self) -> Duration {
        let mut duration = self.elapsed.clone();
        if let Some(last_start) = self.last_start {
            duration += Instant::now() - last_start
        }
        duration
    }
}

fn_defs! {
    /// Builds a stopped stopwatch.
    pub fn new() -> Self {
        Self {
            elapsed: Duration::new(0, 0),
            last_start: None,
        }
    } {
        Self
    }

    /// True if the stopwatch has never been started.
    pub fn is_zero(&self) -> bool {
        self.elapsed.as_secs() == 0 && self.elapsed.subsec_nanos() == 0
    } {
        true
    }

    /// Build a running stopwatch.
    pub fn start_new() -> Self {
        let mut slf = Self::new();
        slf.last_start = Some(Instant::now());
        slf
    } {
        Self
    }

    /// Starts a stopwatch. Does nothing if already running.
    pub fn start(&mut self) {
        if self.last_start.is_none() {
            self.last_start = Some(Instant::now())
        }
        debug_assert!(self.last_start.is_some())
    } {}

    /// Stops a stopwatch. Does nothing if already stopped.
    pub fn stop(&mut self) {
        if let Some(last_start) = std::mem::replace(&mut self.last_start, None) {
            self.elapsed += Instant::now() - last_start
        }
        debug_assert_eq!(self.last_start, None)
    } {}

    /// True if the stopwatch is running.
    pub fn is_running(&self) -> bool {
        self.last_start.is_some()
    } { false }

    /// Resets a stopwatch. Preserves the fact that it is running or not.
    pub fn reset(&mut self) {
        let running = self.is_running();
        *self = Self::new();
        if running {
            self.start()
        }
    } {}

    /// Times some action if not currently running.
    pub fn time<Out>(&mut self, f: impl FnOnce() -> Out) -> Out {
        if !self.is_running() {
            self.start();
            let res = f();
            self.stop();
            res
        } else {
            f()
        }
    } { f() }
}

/// Creates a stopwatch aggregation.
#[macro_export]
macro_rules! new_time_stats {
    (
        $(#[$ty_meta:meta])*
        $ty_vis:vis struct $ty_name:ident {$(
            $(#[$field_meta:meta])*
            $field_vis:vis $field_name:ident => $field_desc:expr,
        )*}
    ) => {
        $(#[$ty_meta])*
        $ty_vis struct $ty_name {$(
            $(#[$field_meta])*
            #[cfg(any(test, feature = "time_stats"))]
            $field_vis $field_name: $crate::time_stats::RealStopwatch,

            $(#[$field_meta])*
            #[cfg(not(any(test, feature = "time_stats")))]
            $field_vis $field_name: $crate::time_stats::FakeStopwatch,
        )*}

        impl $ty_name {
            /// Constructor.
            #[cfg(any(test, feature = "time_stats"))]
            pub fn new() -> Self {
                Self {$(
                    $field_name: $crate::time_stats::RealStopwatch::new(),
                )*}
            }
            /// Constructor.
            #[cfg(not(any(test, feature = "time_stats")))]
            pub fn new() -> Self {
                Self {$(
                    $field_name: $crate::time_stats::FakeStopwatch::new(),
                )*}
            }

            /// Resets all the stopwatches.
            pub fn reset(&mut self) {
                $(
                    self.$field_name.reset();
                )*
            }

            /// True if we are profiling.
            pub const TIME_STATS_ACTIVE: bool = cfg!(any(test, feature = "time_stats"));

            /// Iterates over all stopwatches.
            #[cfg(any(test, feature = "time_stats"))]
            pub fn all_do(
                &self,
                first_do: impl FnOnce(),
                mut action: impl FnMut(&'static str, &$crate::time_stats::RealStopwatch)
            ) {
                first_do();
                $(
                    if !self.$field_name.is_zero() {
                        action($field_desc, &self.$field_name)
                    }
                )*
            }
            /// Iterates over all stopwatches.
            #[cfg(not(any(test, feature = "time_stats")))]
            #[inline]
            pub fn all_do(
                &self,
                _: impl FnOnce(),
                _: impl FnMut(&'static str, &$crate::time_stats::FakeStopwatch)
            ) {
            }
        }
        impl std::fmt::Display for $ty_name {
            fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
                #![allow(unused_assignments)]

                #[allow(unused_mut)]
                let mut pref = "";

                $(
                    write!(
                        fmt, "{}{}: {}",
                        pref,
                        $field_desc,
                        self.$field_name
                    )?;
                    pref = ", ";
                )*
                Ok(())
            }
        }
    };
}

#[cfg(test)]
#[allow(dead_code)]
mod test {
    new_time_stats! {
        /// Profiler.
        pub struct Profiler {
            pub loading => "loading",
            pub parsing => "parsing",
            pub communication => "communication",
        }
    }

    #[test]
    fn basics() {
        let mut profiler = Profiler::new();

        profiler.loading.start();
        profiler.communication.start();
        profiler.loading.reset();
        profiler.communication.stop();
        profiler.loading.stop();

        println!(
            "loading: {}, parsing: {}, communication: {}",
            profiler.loading, profiler.parsing, profiler.communication
        )
    }
}