arnaucube
arnaucube/testudoPublic Self-hosted repository
testudo/src/timer.rs
src/timer.rsRaw
 1#[cfg(feature = "profile")]
 2use colored::Colorize;
 3#[cfg(feature = "profile")]
 4use std::sync::atomic::AtomicUsize;
 5#[cfg(feature = "profile")]
 6use std::{sync::atomic::Ordering, time::Instant};
 7
 8#[cfg(feature = "profile")]
 9pub static CALL_DEPTH: AtomicUsize = AtomicUsize::new(0);
10
11#[cfg(feature = "profile")]
12pub struct Timer {
13  label: String,
14  timer: Instant,
15}
16
17#[cfg(feature = "profile")]
18impl Timer {
19  #[inline(always)]
20  pub fn new(label: &str) -> Self {
21    let timer = Instant::now();
22    CALL_DEPTH.fetch_add(1, Ordering::Relaxed);
23    println!(
24      "{:indent$}{}{}",
25      "",
26      "* ",
27      label.yellow().bold(),
28      indent = 2 * CALL_DEPTH.fetch_add(0, Ordering::Relaxed)
29    );
30    Self {
31      label: label.to_string(),
32      timer,
33    }
34  }
35
36  #[inline(always)]
37  pub fn stop(&self) {
38    let duration = self.timer.elapsed();
39    println!(
40      "{:indent$}{}{} {:?}",
41      "",
42      "* ",
43      self.label.blue().bold(),
44      duration,
45      indent = 2 * CALL_DEPTH.fetch_add(0, Ordering::Relaxed)
46    );
47    CALL_DEPTH.fetch_sub(1, Ordering::Relaxed);
48  }
49
50  #[inline(always)]
51  pub fn print(msg: &str) {
52    CALL_DEPTH.fetch_add(1, Ordering::Relaxed);
53    println!(
54      "{:indent$}{}{}",
55      "",
56      "* ",
57      msg.to_string().green().bold(),
58      indent = 2 * CALL_DEPTH.fetch_add(0, Ordering::Relaxed)
59    );
60    CALL_DEPTH.fetch_sub(1, Ordering::Relaxed);
61  }
62}
63
64#[cfg(not(feature = "profile"))]
65pub struct Timer {
66  _label: String,
67}
68
69#[cfg(not(feature = "profile"))]
70impl Timer {
71  #[inline(always)]
72  pub fn new(label: &str) -> Self {
73    Self {
74      _label: label.to_string(),
75    }
76  }
77
78  #[inline(always)]
79  pub fn stop(&self) {}
80
81  #[inline(always)]
82  pub fn print(_msg: &str) {}
83}