1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#[doc(hidden)]
pub extern crate tracing;

use tracing::{info, span::EnteredSpan};

/// Prints time elapsed since `start` when dropped.
///
/// See [timer] for usages.
pub struct Timer {
    #[cfg(not(target_arch = "wasm32"))]
    _span: EnteredSpan,
    #[cfg(not(target_arch = "wasm32"))]
    start: std::time::Instant,
}

impl Timer {
    /// Don't use this directly. Use [timer] instead.
    pub fn new(_span: EnteredSpan) -> Self {
        Self {
            #[cfg(not(target_arch = "wasm32"))]
            _span,
            #[cfg(not(target_arch = "wasm32"))]
            start: std::time::Instant::now(),
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl Drop for Timer {
    fn drop(&mut self) {
        let dur = self.start.elapsed();
        info!(kind = "perf", "Done in {:?}", dur);
    }
}

/// Creates a timer. For input arguments, see [tracing::span].
///
/// # Convention
///
/// The string passed to `timer!` should start with a verb.
///
/// # Example usage
///
/// ```
/// use swc_timer::timer;
/// # let _logger = testing::init();
/// let _timer = timer!("");
/// ```
///
/// ## With arguments
/// ```
/// use swc_timer::timer;
/// # let _logger = testing::init();
/// let arg = "path";
/// let _timer = timer!("bundle", path = arg);
/// ```
#[macro_export]
macro_rules! timer {
    ($($args:tt)*) => {{
        #[cfg(not(target_arch = "wasm32"))]
        let span = $crate::tracing::span!($crate::tracing::Level::INFO, $($args)*).entered();

        #[cfg(not(target_arch = "wasm32"))]
        $crate::Timer::new(span)
    }};
}