Skip to content

Instantly share code, notes, and snippets.

@Canop
Created January 30, 2020 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Canop/bf35d5da33c6db887fa3811aba65020f to your computer and use it in GitHub Desktop.
Save Canop/bf35d5da33c6db887fa3811aba65020f to your computer and use it in GitHub Desktop.
/// print the time that executing $timed took
/// but only when the log level is "debug".
/// The goal of this macro is to avoid doing useless
/// Instant::now in non Debug executions.
///
/// Examples:
/// ```
/// let sum = time!(
/// "summing",
/// 2 + 2 // this is super hard
/// );
/// let mult = time!(3 * 4);
/// ```
macro_rules! time {
($timed: expr) => {{
if log_enabled!(log::Level::Debug) {
use std::time::Instant;
let start = Instant::now();
let value = $timed;
debug!("{} took {:?}", stringify!($timed), start.elapsed());
value
} else {
$timed
}
}};
($name: expr, $timed: expr $(,)?) => {{
if log_enabled!(log::Level::Debug) {
use std::time::Instant;
let start = Instant::now();
let value = $timed;
debug!("{} took {:?}", $name, start.elapsed());
value
} else {
$timed
}
}};
($cat: expr, $name :expr, $timed: expr $(,)?) => {{
if log_enabled!(log::Level::Debug) {
use std::time::Instant;
let start = Instant::now();
let value = $timed;
debug!("{} on {:?} took {:?}", $cat, $name, start.elapsed());
value
} else {
$timed
}
}};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment