gameloop_timing/
looptimer.rs

1//! A basic timer struct for looping constructs.
2
3use super::*;
4
5/// Wraps the variables necessary to keep track of loop timings.
6pub struct LoopTimer {
7    /// The last start of the loop.
8    pub start: Instant,
9    
10    /// The last end of the loop.
11    pub end: Instant,
12    
13    /// The last time/duration of the loop.
14    pub time: Duration,
15    
16    /// The intended time/duration of the loop.
17    pub target: Duration,
18    
19    /// How many iterations have been done.
20    pub count: u32,
21}
22
23impl LoopTimer {
24    /// Creates a new looptimer with the given target loop duration.
25    pub fn new(target: Duration) -> Self {
26        let now = Instant::now();
27        Self {
28            count: 0,
29            start: now,
30            end: now + target,
31            time: target,
32            target
33        }
34    }
35    
36    /// Creates a new looptimer with the given target loop duration and a starting instant.
37    pub fn new_from(now: Instant, target: Duration) -> Self {
38        Self {
39            count: 0,
40            start: now,
41            end: now + target,
42            time: target,
43            target
44        }
45    }
46    
47    /// Resets the loop-counter.
48    pub fn reset_count(&mut self) {
49        self.count = 0;
50    }
51    
52    /// Begins the loop measurement.
53    pub fn start(&mut self) {
54        self.start = Instant::now();
55    }
56    
57    /// Finishes the loop measurement.
58    pub fn end(&mut self) {
59        self.end = Instant::now();
60        self.time = self.end.saturating_duration_since(self.end);
61        self.count += 1;
62    }
63    
64    /// Returns the length of the last loop iteration, in nanoseconds.
65    pub fn length(&self) -> u128 {
66        self.time.as_nanos()
67    }
68}