vibesql_executor/
profiling.rs

1//! Performance profiling utilities for understanding bottlenecks
2
3use instant::Instant;
4use std::sync::atomic::{AtomicBool, Ordering};
5
6/// Global flag to enable/disable profiling (disabled by default)
7/// Set VIBESQL_PROFILE=1 environment variable to enable
8static PROFILING_ENABLED: AtomicBool = AtomicBool::new(false);
9
10/// Initialize profiling based on environment variable
11pub fn init() {
12    if std::env::var("VIBESQL_PROFILE").is_ok() {
13        PROFILING_ENABLED.store(true, Ordering::Relaxed);
14        eprintln!("[PROFILE] Profiling enabled");
15    }
16}
17
18/// Check if profiling is enabled
19pub fn is_enabled() -> bool {
20    PROFILING_ENABLED.load(Ordering::Relaxed)
21}
22
23/// A profiling timer that logs elapsed time when dropped
24pub struct ProfileTimer {
25    label: &'static str,
26    start: Instant,
27    enabled: bool,
28}
29
30impl ProfileTimer {
31    /// Create a new profiling timer
32    pub fn new(label: &'static str) -> Self {
33        let enabled = is_enabled();
34        Self { label, start: Instant::now(), enabled }
35    }
36}
37
38impl Drop for ProfileTimer {
39    fn drop(&mut self) {
40        if self.enabled {
41            let elapsed = self.start.elapsed();
42            eprintln!(
43                "[PROFILE] {} took {:.3}ms ({:.0}µs)",
44                self.label,
45                elapsed.as_secs_f64() * 1000.0,
46                elapsed.as_micros()
47            );
48        }
49    }
50}
51
52/// Macro to create a profiling scope
53#[macro_export]
54macro_rules! profile {
55    ($label:expr) => {
56        let _timer = $crate::profiling::ProfileTimer::new($label);
57    };
58}