novel_api/common/utils/
timing.rs

1use std::time::SystemTime;
2
3use crate::Error;
4
5/// Timing tools for performance testing
6#[must_use]
7pub struct Timing {
8    now: SystemTime,
9}
10
11impl Default for Timing {
12    fn default() -> Self {
13        Self::new()
14    }
15}
16
17impl Timing {
18    /// Create a Timing
19    pub fn new() -> Self {
20        Self {
21            now: SystemTime::now(),
22        }
23    }
24
25    /// Get the time difference from the creation time, and reset the creation time to the current time
26    #[inline]
27    pub fn elapsed(&mut self) -> Result<String, Error> {
28        let result = self.elapsed_str()?;
29        self.now = SystemTime::now();
30
31        Ok(result)
32    }
33
34    #[inline]
35    fn elapsed_str(&self) -> Result<String, Error> {
36        let time = self.now.elapsed()?;
37
38        let mut elapsed = time.as_millis();
39        let mut unit = "ms";
40
41        if elapsed <= 1 {
42            elapsed = time.as_micros();
43            unit = "μs";
44        }
45        if elapsed <= 1 {
46            elapsed = time.as_nanos();
47            unit = "ns";
48        }
49
50        Ok(format!("{elapsed}{unit}"))
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn timing() -> Result<(), Error> {
60        let mut timing = Timing::new();
61        let _ = timing.elapsed()?;
62
63        Ok(())
64    }
65}