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,
26    /// and reset the creation time to the current time
27    #[inline]
28    pub fn elapsed(&mut self) -> Result<String, Error> {
29        let result = self.elapsed_str()?;
30        self.now = SystemTime::now();
31
32        Ok(result)
33    }
34
35    #[inline]
36    fn elapsed_str(&self) -> Result<String, Error> {
37        let time = self.now.elapsed()?;
38
39        let mut elapsed = time.as_millis();
40        let mut unit = "ms";
41
42        if elapsed <= 1 {
43            elapsed = time.as_micros();
44            unit = "μs";
45        }
46        if elapsed <= 1 {
47            elapsed = time.as_nanos();
48            unit = "ns";
49        }
50
51        Ok(format!("{elapsed}{unit}"))
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn timing() -> Result<(), Error> {
61        let mut timing = Timing::new();
62        let _ = timing.elapsed()?;
63
64        Ok(())
65    }
66}