Created
July 6, 2023 17:56
-
-
Save PY44N/a54fdc5f29100f700d715b7486c1c0ae to your computer and use it in GitHub Desktop.
A simple function for profiling Rust code
This file contains 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 lazy_static::lazy_static; | |
lazy_static! { | |
static ref PROFILED_SPEEDS: Mutex<HashMap<String, Vec<u64>>> = Mutex::new(HashMap::new()); | |
} | |
fn profile<T>(name: &str, test: &mut impl FnMut() -> T) -> T { | |
let start = SystemTime::now() | |
.duration_since(UNIX_EPOCH) | |
.unwrap() | |
.as_millis() as u64; | |
let ret: T = test(); | |
let finish_time: u64 = SystemTime::now() | |
.duration_since(UNIX_EPOCH) | |
.unwrap() | |
.as_millis() as u64 | |
- start; | |
let mut map = PROFILED_SPEEDS.lock().unwrap(); | |
let avg = if map.contains_key(name) { | |
let times = map.get(name).unwrap(); | |
let mut sum = 0; | |
for time in times { | |
sum += time; | |
} | |
sum / times.len() as u64 | |
} else { | |
0 | |
}; | |
println!("{} finished in {}ms, avg: {}ms", name, finish_time, avg); | |
if map.contains_key(name) { | |
map.get_mut(name).unwrap().push(finish_time); | |
} else { | |
map.insert(name.to_owned(), vec![finish_time]); | |
} | |
ret | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment