-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Remove dead code #4145
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Remove dead code #4145
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
7623db1
minor clenup
matklad b3e9f3d
Move hprof to a separate file
matklad 726938f
Simplify hprof
matklad 95b989e
Simplify
matklad 0f099ea
Fix panic in NoSuchField diagnostic
matklad bd9ede0
Extract messy tree handling out of profiling code
matklad 0ac5ed5
Remove dead code
matklad File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,246 @@ | ||
//! Simple hierarchical profiler | ||
use once_cell::sync::Lazy; | ||
use std::{ | ||
cell::RefCell, | ||
collections::{BTreeMap, HashSet}, | ||
io::{stderr, Write}, | ||
sync::{ | ||
atomic::{AtomicBool, Ordering}, | ||
RwLock, | ||
}, | ||
time::{Duration, Instant}, | ||
}; | ||
|
||
use crate::tree::{Idx, Tree}; | ||
|
||
/// Filtering syntax | ||
/// env RA_PROFILE=* // dump everything | ||
/// env RA_PROFILE=foo|bar|baz // enabled only selected entries | ||
/// env RA_PROFILE=*@3>10 // dump everything, up to depth 3, if it takes more than 10 ms | ||
pub fn init() { | ||
let spec = std::env::var("RA_PROFILE").unwrap_or_default(); | ||
init_from(&spec); | ||
} | ||
|
||
pub fn init_from(spec: &str) { | ||
let filter = if spec.is_empty() { Filter::disabled() } else { Filter::from_spec(spec) }; | ||
filter.install(); | ||
} | ||
|
||
pub type Label = &'static str; | ||
|
||
/// This function starts a profiling scope in the current execution stack with a given description. | ||
/// It returns a Profile structure and measure elapsed time between this method invocation and Profile structure drop. | ||
/// It supports nested profiling scopes in case when this function invoked multiple times at the execution stack. In this case the profiling information will be nested at the output. | ||
/// Profiling information is being printed in the stderr. | ||
/// | ||
/// # Example | ||
/// ``` | ||
/// use ra_prof::{profile, set_filter, Filter}; | ||
/// | ||
/// let f = Filter::from_spec("profile1|profile2@2"); | ||
/// set_filter(f); | ||
/// profiling_function1(); | ||
/// | ||
/// fn profiling_function1() { | ||
/// let _p = profile("profile1"); | ||
/// profiling_function2(); | ||
/// } | ||
/// | ||
/// fn profiling_function2() { | ||
/// let _p = profile("profile2"); | ||
/// } | ||
/// ``` | ||
/// This will print in the stderr the following: | ||
/// ```text | ||
/// 0ms - profile | ||
/// 0ms - profile2 | ||
/// ``` | ||
pub fn profile(label: Label) -> Profiler { | ||
assert!(!label.is_empty()); | ||
let enabled = PROFILING_ENABLED.load(Ordering::Relaxed) | ||
&& PROFILE_STACK.with(|stack| stack.borrow_mut().push(label)); | ||
let label = if enabled { Some(label) } else { None }; | ||
Profiler { label, detail: None } | ||
} | ||
|
||
pub struct Profiler { | ||
label: Option<Label>, | ||
detail: Option<String>, | ||
} | ||
|
||
impl Profiler { | ||
pub fn detail(mut self, detail: impl FnOnce() -> String) -> Profiler { | ||
if self.label.is_some() { | ||
self.detail = Some(detail()) | ||
} | ||
self | ||
} | ||
} | ||
|
||
impl Drop for Profiler { | ||
fn drop(&mut self) { | ||
match self { | ||
Profiler { label: Some(label), detail } => { | ||
PROFILE_STACK.with(|stack| { | ||
stack.borrow_mut().pop(label, detail.take()); | ||
}); | ||
} | ||
Profiler { label: None, .. } => (), | ||
} | ||
} | ||
} | ||
|
||
static PROFILING_ENABLED: AtomicBool = AtomicBool::new(false); | ||
static FILTER: Lazy<RwLock<Filter>> = Lazy::new(Default::default); | ||
thread_local!(static PROFILE_STACK: RefCell<ProfileStack> = RefCell::new(ProfileStack::new())); | ||
|
||
#[derive(Default, Clone, Debug)] | ||
struct Filter { | ||
depth: usize, | ||
allowed: HashSet<String>, | ||
longer_than: Duration, | ||
version: usize, | ||
} | ||
|
||
impl Filter { | ||
fn disabled() -> Filter { | ||
Filter::default() | ||
} | ||
|
||
fn from_spec(mut spec: &str) -> Filter { | ||
let longer_than = if let Some(idx) = spec.rfind('>') { | ||
let longer_than = spec[idx + 1..].parse().expect("invalid profile longer_than"); | ||
spec = &spec[..idx]; | ||
Duration::from_millis(longer_than) | ||
} else { | ||
Duration::new(0, 0) | ||
}; | ||
|
||
let depth = if let Some(idx) = spec.rfind('@') { | ||
let depth: usize = spec[idx + 1..].parse().expect("invalid profile depth"); | ||
spec = &spec[..idx]; | ||
depth | ||
} else { | ||
999 | ||
}; | ||
let allowed = | ||
if spec == "*" { HashSet::new() } else { spec.split('|').map(String::from).collect() }; | ||
Filter { depth, allowed, longer_than, version: 0 } | ||
} | ||
|
||
fn install(mut self) { | ||
PROFILING_ENABLED.store(self.depth > 0, Ordering::SeqCst); | ||
let mut old = FILTER.write().unwrap(); | ||
self.version = old.version + 1; | ||
*old = self; | ||
} | ||
} | ||
|
||
struct ProfileStack { | ||
starts: Vec<Instant>, | ||
filter: Filter, | ||
messages: Tree<Message>, | ||
} | ||
|
||
#[derive(Default)] | ||
struct Message { | ||
duration: Duration, | ||
label: Label, | ||
detail: Option<String>, | ||
} | ||
|
||
impl ProfileStack { | ||
fn new() -> ProfileStack { | ||
ProfileStack { starts: Vec::new(), messages: Tree::default(), filter: Default::default() } | ||
} | ||
|
||
fn push(&mut self, label: Label) -> bool { | ||
if self.starts.is_empty() { | ||
if let Ok(f) = FILTER.try_read() { | ||
if f.version > self.filter.version { | ||
self.filter = f.clone(); | ||
} | ||
}; | ||
} | ||
if self.starts.len() > self.filter.depth { | ||
return false; | ||
} | ||
let allowed = &self.filter.allowed; | ||
if self.starts.is_empty() && !allowed.is_empty() && !allowed.contains(label) { | ||
return false; | ||
} | ||
|
||
self.starts.push(Instant::now()); | ||
self.messages.start(); | ||
true | ||
} | ||
|
||
pub fn pop(&mut self, label: Label, detail: Option<String>) { | ||
let start = self.starts.pop().unwrap(); | ||
let duration = start.elapsed(); | ||
let level = self.starts.len(); | ||
self.messages.finish(Message { duration, label, detail }); | ||
if level == 0 { | ||
let longer_than = self.filter.longer_than; | ||
// Convert to millis for comparison to avoid problems with rounding | ||
// (otherwise we could print `0ms` despite user's `>0` filter when | ||
// `duration` is just a few nanos). | ||
if duration.as_millis() > longer_than.as_millis() { | ||
let stderr = stderr(); | ||
if let Some(root) = self.messages.root() { | ||
print(&self.messages, root, 0, longer_than, &mut stderr.lock()); | ||
} | ||
} | ||
self.messages.clear(); | ||
assert!(self.starts.is_empty()) | ||
} | ||
} | ||
} | ||
|
||
fn print( | ||
tree: &Tree<Message>, | ||
curr: Idx<Message>, | ||
level: u32, | ||
longer_than: Duration, | ||
out: &mut impl Write, | ||
) { | ||
let current_indent = " ".repeat(level as usize); | ||
let detail = tree[curr].detail.as_ref().map(|it| format!(" @ {}", it)).unwrap_or_default(); | ||
writeln!( | ||
out, | ||
"{}{:5}ms - {}{}", | ||
current_indent, | ||
tree[curr].duration.as_millis(), | ||
tree[curr].label, | ||
detail, | ||
) | ||
.expect("printing profiling info"); | ||
|
||
let mut accounted_for = Duration::default(); | ||
let mut short_children = BTreeMap::new(); // Use `BTreeMap` to get deterministic output. | ||
for child in tree.children(curr) { | ||
accounted_for += tree[child].duration; | ||
|
||
if tree[child].duration.as_millis() > longer_than.as_millis() { | ||
print(tree, child, level + 1, longer_than, out) | ||
} else { | ||
let (total_duration, cnt) = | ||
short_children.entry(tree[child].label).or_insert((Duration::default(), 0)); | ||
*total_duration += tree[child].duration; | ||
*cnt += 1; | ||
} | ||
} | ||
|
||
for (child_msg, (duration, count)) in short_children.iter() { | ||
let millis = duration.as_millis(); | ||
writeln!(out, " {}{:5}ms - {} ({} calls)", current_indent, millis, child_msg, count) | ||
.expect("printing profiling info"); | ||
} | ||
|
||
let unaccounted = tree[curr].duration - accounted_for; | ||
if tree.children(curr).next().is_some() && unaccounted > longer_than { | ||
writeln!(out, " {}{:5}ms - ???", current_indent, unaccounted.as_millis()) | ||
.expect("printing profiling info"); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What is the reason for this assert? This if checks that the
starts
stack is empty in the if condition