Created
January 17, 2018 21:09
-
-
Save greyblake/9739e3bebb6ef36aeff4efa1e943b856 to your computer and use it in GitHub Desktop.
Log exec
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
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