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
// Used to keep track of time. #[derive(Debug, Default, Clone, Copy)] pub struct TimeTracker { now_sec_f64: f64, } /// Maximum number of seconds we can track. This is related /// to the limit of a mantissa in 64-bit IEEE numbers, which /// is about 10^15. Since we count in msec, we have to divide /// to take away 3 digits. This is still several centuries. pub const TIME_TRACKER_MAX_SEC: f64 = 1e12; impl TimeTracker { /// Create a time tracker. /// /// # Examples /// /// ``` /// use babalcore::*; /// /// let _tt = TimeTracker::new(); /// ``` pub fn new() -> TimeTracker { TimeTracker::default() } /// Add time to the time tracker. This is typically something /// you'd call each time there's a process(delta). /// /// # Examples /// /// ``` /// use babalcore::*; /// /// let mut tt = TimeTracker::new(); /// tt.add(0.01); /// assert_eq!(0.01, tt.now_sec()); /// ``` pub fn add(&mut self, delta: f64) { self.now_sec_f64 += delta; if self.now_sec_f64 < 0.0 || self.now_sec_f64 >= TIME_TRACKER_MAX_SEC { self.now_sec_f64 = 0.0; } } /// Get the number of seconds since start of time. /// /// # Examples /// /// ``` /// use babalcore::*; /// /// let mut tt = TimeTracker::new(); /// assert_eq!(0.0, tt.now_sec()); /// tt.add(0.003); /// assert_eq!(0.003, tt.now_sec()); /// ``` pub fn now_sec(&self) -> f64 { self.now_sec_f64 } /// Get the number of milliseconds since start of time. /// /// # Examples /// /// ``` /// use babalcore::*; /// /// let mut tt = TimeTracker::new(); /// assert_eq!(0, tt.now_msec()); /// tt.add(0.003); /// assert_eq!(3, tt.now_msec()); /// ``` pub fn now_msec(&self) -> i64 { (self.now_sec_f64 * 1000.0) as i64 } } impl std::fmt::Display for TimeTracker { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let now_msec = self.now_msec(); write!(f, "{}.{:03}", now_msec / 1000, now_msec % 1000) } } #[cfg(test)] mod tests { use crate::*; #[test] fn test_fmt() { let mut tt = TimeTracker::new(); tt.add(2.0); tt.add(0.05); assert_eq!("2.050", format!("{}", tt)); } }