turbo_tasks/
duration_span.rs

1use std::time::Instant;
2
3/// Guard that emits a tracing event when dropped with the duration of the
4/// lifetime of the guard.
5pub struct DurationSpanGuard<F: FnOnce(u64)> {
6    start: Instant,
7    f: Option<F>,
8}
9
10impl<F: FnOnce(u64)> DurationSpanGuard<F> {
11    pub fn new(f: F) -> Self {
12        Self {
13            start: Instant::now(),
14            f: Some(f),
15        }
16    }
17}
18
19impl<F: FnOnce(u64)> Drop for DurationSpanGuard<F> {
20    fn drop(&mut self) {
21        if let Some(f) = self.f.take() {
22            f(self.start.elapsed().as_micros() as u64);
23        }
24    }
25}
26
27/// Creates a event-based span that traces a certain duration (lifetime of the
28/// guard). It's not a real span, which means it can be used across threads.
29///
30/// It will trace a duration and not the time the cpu is doing actual work. This
31/// way it can be used to trace non-cpu-time or time that is spend in other
32/// processes.
33#[macro_export]
34macro_rules! duration_span {
35    ($name:literal) => {
36        turbo_tasks::duration_span::DurationSpanGuard::new(|duration| {
37            turbo_tasks::macro_helpers::tracing::info!(name = $name, duration = duration);
38        })
39    };
40    ($name:literal, $($arg:tt)+) => {
41        turbo_tasks::duration_span::DurationSpanGuard::new(|duration| {
42            turbo_tasks::macro_helpers::tracing::info!(name = $name, $($arg)+, duration = duration);
43        })
44    };
45}