Skip to content

Instantly share code, notes, and snippets.

@greyblake
Created January 17, 2018 21:09
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 greyblake/9739e3bebb6ef36aeff4efa1e943b856 to your computer and use it in GitHub Desktop.
Save greyblake/9739e3bebb6ef36aeff4efa1e943b856 to your computer and use it in GitHub Desktop.
Log exec
use std::time::Duration;
use std::time::Instant;
// Executes `func` and logs warning or error message if it takes longer than specified.
pub fn log_exec<F, T>(label: &str, warn_millis: u64, error_millis: u64, func: F) -> T where F: FnOnce() -> T {
let warn_duration = Duration::from_millis(warn_millis);
let error_duration = Duration::from_millis(error_millis);
let start = Instant::now();
let output = func();
let end = Instant::now();
let duration = end - start;
if duration > error_duration {
error!("`{}` took much longer than expected: {:2.2} secs", label, to_secs(duration));
} else if duration > warn_duration {
warn!("`{}` took longer than expected: {:2.2} secs", label, to_secs(duration));
}
output
}
fn to_secs(duration: Duration) -> f64 {
let secs = duration.as_secs() as f64;
let nanos = duration.subsec_nanos() as f64;
secs + nanos / 1000_000_000.0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment