Skip to content

Instantly share code, notes, and snippets.

@andreievg
Created August 22, 2023 23:31
Show Gist options
  • Save andreievg/71bb0be84c41d48b181a01a7e6bb3dcb to your computer and use it in GitHub Desktop.
Save andreievg/71bb0be84c41d48b181a01a7e6bb3dcb to your computer and use it in GitHub Desktop.
Rust bench helper
pub fn bench_point(identifier: &str) {
BENCH_POINTS.lock().unwrap().push(BenchPoint {
identifier: identifier.to_string(),
time: Utc::now(),
})
}
pub static BENCH_POINTS: Mutex<Vec<BenchPoint>> = Mutex::new(Vec::new());
// ideally this would be a macro to capture file and location
pub fn bench_point(identifier: &str) {
BENCH_POINTS.lock().unwrap().push(BenchPoint {
identifier: identifier.to_string(),
time: Utc::now(),
})
}
pub fn bench_clear(identifier: &str) {
BENCH_POINTS.lock().unwrap().push(BenchPoint {
identifier: identifier.to_string(),
time: Utc::now(),
})
}
pub fn bench_results() {
let mut bench_points = BENCH_POINTS.lock().unwrap();
bench_points.sort_by(|a, b| a.time.cmp(&b.time));
let Some(start_time) = bench_points.first() else {
return;
};
let mut previous_time = start_time.time;
for BenchPoint { identifier, time } in bench_points.iter() {
let diff_from_start = *time - start_time.time;
let diff_from_previous = *time - previous_time;
println!("{identifier: <30}\t{diff_from_start: <10}\t{diff_from_previous: <10}");
previous_time = *time;
}
}
@andreievg
Copy link
Author

andreievg commented Aug 22, 2023

To use:

fn do_it() {
    bench_point("step 1 start")
    // do some work step 1
    bench_point("step 1 stop")

    bench_point("step 2 start")
    // do some work step 2
    bench_point("step 2 stop")

    bench_result()
}

There is soo much more that can be improved, but was sufficient for quick use case I had.

Improvements:

  • optimise api (can be step based ? and can create instance of bench for a method)
  • can clear bench points
  • clear
  • use macro (can record line numbers and file, and this can lead to hint display in vs code of actual result times, and maybe don't need to specify identifier at this stage)
  • toggle bench on and off
  • time diffs to be easier to read

@Chris-Petty
Copy link

Tangential RND topic: flame graph might be kewl https://github.com/flamegraph-rs/flamegraph

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment