Skip to content

Instantly share code, notes, and snippets.

@arifd
Created March 2, 2023 13:48
Show Gist options
  • Save arifd/5b92ecfda8fb558d94c1c774adbeb060 to your computer and use it in GitHub Desktop.
Save arifd/5b92ecfda8fb558d94c1c774adbeb060 to your computer and use it in GitHub Desktop.
log slow functions, optimized out in release, example of cancelling a thread
use std::{
sync::mpsc,
time::{Duration, Instant},
};
/// Warns on any function that is behaving slow
///
/// Useful for when your code appears to be getting stuck somewhere
/// and you want a fast "debug print" way of knowing where.
#[inline]
pub fn with_timing<F, G>(delay: Duration, mut f: F) -> G
where
F: FnMut() -> G,
{
if cfg!(debug_assertions) {
let (tx, rx) = mpsc::channel();
let span = tracing::Span::current();
let now = Instant::now();
std::thread::spawn(move || {
let _span = span.entered();
while let Err(mpsc::TryRecvError::Empty) = rx.try_recv() {
let elapsed = now.elapsed();
if elapsed > delay {
tracing::warn!(?elapsed, "SLOW");
}
std::thread::sleep(Duration::from_secs(1));
}
});
let result = f();
tx.send(()).ok();
result
} else {
f()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment