ai/
profiling.rs

1use std::time::{Duration, Instant};
2
3use colored::Colorize;
4
5use crate::debug_output;
6
7pub struct Profile {
8  start: Instant,
9  name:  String
10}
11
12impl Profile {
13  pub fn new(name: impl Into<String>) -> Self {
14    Self { start: Instant::now(), name: name.into() }
15  }
16
17  pub fn elapsed(&self) -> Duration {
18    self.start.elapsed()
19  }
20}
21
22impl Drop for Profile {
23  fn drop(&mut self) {
24    let duration = self.elapsed();
25
26    // Record timing in debug session if available
27    debug_output::record_timing(&self.name, duration);
28
29    // Always show profiling in debug builds, otherwise respect log level
30    #[cfg(debug_assertions)]
31    {
32      eprintln!("{}: {:.2?}", self.name.blue(), duration);
33    }
34
35    #[cfg(not(debug_assertions))]
36    if log::log_enabled!(log::Level::Debug) {
37      eprintln!("{}: {:.2?}", self.name.blue(), duration);
38    }
39  }
40}
41
42#[macro_export]
43macro_rules! profile {
44  ($name:expr) => {
45    let _profile = $crate::Profile::new($name);
46  };
47}
48
49/// Helper function to profile a block of code and return its result
50pub fn profile_fn<F, T>(name: &str, f: F) -> T
51where
52  F: FnOnce() -> T
53{
54  let profile = Profile::new(name);
55  let result = f();
56  drop(profile);
57  result
58}