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
|
use std::fmt::{Display, Error, Formatter};
/// A timer.
#[derive(Copy, Clone, Debug, Default)]
pub struct Timer {
time: f64,
#[allow(dead_code)] // The field isn’t used if the `profiler` feature isn’t enabled.
start: Option<f64>,
}
impl Timer {
/// Creates a new timer initialized to zero and not started.
pub fn new() -> Self {
Timer {
time: 0.0,
start: None,
}
}
/// Resets the timer to 0.
pub fn reset(&mut self) {
self.time = 0.0
}
/// Start the timer.
pub fn start(&mut self) {
#[cfg(feature = "profiler")]
{
self.time = 0.0;
self.start = Some(instant::now());
}
}
/// Pause the timer.
pub fn pause(&mut self) {
#[cfg(feature = "profiler")]
{
if let Some(start) = self.start {
self.time += instant::now() - start;
}
self.start = None;
}
}
/// Resume the timer.
pub fn resume(&mut self) {
#[cfg(feature = "profiler")]
{
self.start = Some(instant::now());
}
}
/// The measured time between the last `.start()` and `.pause()` calls.
pub fn time(&self) -> f64 {
self.time
}
}
impl Display for Timer {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
write!(f, "{}s", self.time)
}
}
|