1 //! Simple hierarchical profiler
2 use once_cell::sync::Lazy;
5 collections::{BTreeMap, HashSet},
8 atomic::{AtomicBool, Ordering},
11 time::{Duration, Instant},
14 use crate::tree::{Idx, Tree};
17 /// env RA_PROFILE=* // dump everything
18 /// env RA_PROFILE=foo|bar|baz // enabled only selected entries
19 /// env RA_PROFILE=*@3>10 // dump everything, up to depth 3, if it takes more than 10 ms
21 let spec = std::env::var("RA_PROFILE").unwrap_or_default();
25 pub fn init_from(spec: &str) {
26 let filter = if spec.is_empty() { Filter::disabled() } else { Filter::from_spec(spec) };
30 type Label = &'static str;
32 /// This function starts a profiling scope in the current execution stack with a given description.
33 /// It returns a `Profile` struct that measures elapsed time between this method invocation and `Profile` struct drop.
34 /// It supports nested profiling scopes in case when this function is invoked multiple times at the execution stack.
35 /// In this case the profiling information will be nested at the output.
36 /// Profiling information is being printed in the stderr.
40 /// profile::init_from("profile1|profile2@2");
41 /// profiling_function1();
43 /// fn profiling_function1() {
44 /// let _p = profile::span("profile1");
45 /// profiling_function2();
48 /// fn profiling_function2() {
49 /// let _p = profile::span("profile2");
52 /// This will print in the stderr the following:
57 pub fn span(label: Label) -> ProfileSpan {
58 assert!(!label.is_empty());
60 if PROFILING_ENABLED.load(Ordering::Relaxed)
61 && PROFILE_STACK.with(|stack| stack.borrow_mut().push(label))
63 ProfileSpan(Some(ProfilerImpl { label, detail: None }))
69 pub struct ProfileSpan(Option<ProfilerImpl>);
73 detail: Option<String>,
77 pub fn detail(mut self, detail: impl FnOnce() -> String) -> ProfileSpan {
78 if let Some(profiler) = &mut self.0 {
79 profiler.detail = Some(detail())
85 impl Drop for ProfilerImpl {
87 PROFILE_STACK.with(|it| it.borrow_mut().pop(self.label, self.detail.take()));
91 static PROFILING_ENABLED: AtomicBool = AtomicBool::new(false);
92 static FILTER: Lazy<RwLock<Filter>> = Lazy::new(Default::default);
93 thread_local!(static PROFILE_STACK: RefCell<ProfileStack> = RefCell::new(ProfileStack::new()));
95 #[derive(Default, Clone, Debug)]
98 allowed: HashSet<String>,
99 longer_than: Duration,
104 fn disabled() -> Filter {
108 fn from_spec(mut spec: &str) -> Filter {
109 let longer_than = if let Some(idx) = spec.rfind('>') {
110 let longer_than = spec[idx + 1..].parse().expect("invalid profile longer_than");
112 Duration::from_millis(longer_than)
117 let depth = if let Some(idx) = spec.rfind('@') {
118 let depth: usize = spec[idx + 1..].parse().expect("invalid profile depth");
125 if spec == "*" { HashSet::new() } else { spec.split('|').map(String::from).collect() };
126 Filter { depth, allowed, longer_than, version: 0 }
129 fn install(mut self) {
130 PROFILING_ENABLED.store(self.depth > 0, Ordering::SeqCst);
131 let mut old = FILTER.write().unwrap();
132 self.version = old.version + 1;
137 struct ProfileStack {
138 starts: Vec<Instant>,
140 messages: Tree<Message>,
147 detail: Option<String>,
151 fn new() -> ProfileStack {
152 ProfileStack { starts: Vec::new(), messages: Tree::default(), filter: Default::default() }
155 fn push(&mut self, label: Label) -> bool {
156 if self.starts.is_empty() {
157 if let Ok(f) = FILTER.try_read() {
158 if f.version > self.filter.version {
159 self.filter = f.clone();
163 if self.starts.len() > self.filter.depth {
166 let allowed = &self.filter.allowed;
167 if self.starts.is_empty() && !allowed.is_empty() && !allowed.contains(label) {
171 self.starts.push(Instant::now());
172 self.messages.start();
176 fn pop(&mut self, label: Label, detail: Option<String>) {
177 let start = self.starts.pop().unwrap();
178 let duration = start.elapsed();
179 self.messages.finish(Message { duration, label, detail });
180 if self.starts.is_empty() {
181 let longer_than = self.filter.longer_than;
182 // Convert to millis for comparison to avoid problems with rounding
183 // (otherwise we could print `0ms` despite user's `>0` filter when
184 // `duration` is just a few nanos).
185 if duration.as_millis() > longer_than.as_millis() {
186 if let Some(root) = self.messages.root() {
187 print(&self.messages, root, 0, longer_than, &mut stderr().lock());
190 self.messages.clear();
196 tree: &Tree<Message>,
199 longer_than: Duration,
200 out: &mut impl Write,
202 let current_indent = " ".repeat(level as usize);
203 let detail = tree[curr].detail.as_ref().map(|it| format!(" @ {}", it)).unwrap_or_default();
208 tree[curr].duration.as_millis(),
212 .expect("printing profiling info");
214 let mut accounted_for = Duration::default();
215 let mut short_children = BTreeMap::new(); // Use `BTreeMap` to get deterministic output.
216 for child in tree.children(curr) {
217 accounted_for += tree[child].duration;
219 if tree[child].duration.as_millis() > longer_than.as_millis() {
220 print(tree, child, level + 1, longer_than, out)
222 let (total_duration, cnt) =
223 short_children.entry(tree[child].label).or_insert((Duration::default(), 0));
224 *total_duration += tree[child].duration;
229 for (child_msg, (duration, count)) in short_children.iter() {
230 let millis = duration.as_millis();
231 writeln!(out, " {}{:5}ms - {} ({} calls)", current_indent, millis, child_msg, count)
232 .expect("printing profiling info");
235 let unaccounted = tree[curr].duration - accounted_for;
236 if tree.children(curr).next().is_some() && unaccounted > longer_than {
237 writeln!(out, " {}{:5}ms - ???", current_indent, unaccounted.as_millis())
238 .expect("printing profiling info");