kaspa_core/
time.rs

1use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
2
3/// Returns the number of milliseconds since UNIX EPOCH
4#[inline]
5pub fn unix_now() -> u64 {
6    SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64
7}
8
9/// Stopwatch which reports on drop if the timed operation passed the threshold `TR` in milliseconds
10pub struct Stopwatch<const TR: u64 = 1000> {
11    name: &'static str,
12    start: Instant,
13}
14
15impl Stopwatch {
16    pub fn new(name: &'static str) -> Self {
17        Self { name, start: Instant::now() }
18    }
19}
20
21impl<const TR: u64> Stopwatch<TR> {
22    pub fn with_threshold(name: &'static str) -> Self {
23        Self { name, start: Instant::now() }
24    }
25
26    pub fn elapsed(&self) -> Duration {
27        self.start.elapsed()
28    }
29}
30
31impl<const TR: u64> Drop for Stopwatch<TR> {
32    fn drop(&mut self) {
33        let elapsed = self.start.elapsed();
34        if elapsed > Duration::from_millis(TR) {
35            kaspa_core::trace!("[{}] Abnormal time: {:#?}", self.name, elapsed);
36        }
37    }
38}