Skip to content

Commit

Permalink
Time recorder merge duplicate descriptions
Browse files Browse the repository at this point in the history
  • Loading branch information
zakstucke committed Jan 17, 2024
1 parent 73ba4f7 commit 51fd52e
Showing 1 changed file with 46 additions and 6 deletions.
52 changes: 46 additions & 6 deletions rust/bitbazaar/timing/recorder.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::sync::Arc;
use std::{collections::HashMap, sync::Arc};

use once_cell::sync::Lazy;
use parking_lot::Mutex;
Expand All @@ -9,10 +9,50 @@ use crate::{err, errors::TracedErr, timing::format_duration};
/// A global time recorder, used by the timeit! macro.
pub static GLOBAL_TIME_RECORDER: Lazy<TimeRecorder> = Lazy::new(TimeRecorder::new);

#[derive(Default)]
struct Logs {
next_log_index: usize,
// Hashmap to combine logs with the same description:
logs: HashMap<String, Log>,
}

impl Logs {
/// Add a new log, will add to an existing if the description is the same as something that's already in there.
fn add_log(&mut self, description: &str, duration: std::time::Duration) {
if let Some(log) = self.logs.get_mut(description) {
log.duration += duration;
} else {
self.logs.insert(
description.to_owned(),
Log {
duration,
log_index: self.next_log_index,
},
);
self.next_log_index += 1;
}
}

fn sorted_logs(&self) -> Vec<(&str, &Log)> {
let mut logs: Vec<(&str, &Log)> = self
.logs
.iter()
.map(|(description, log)| (description.as_str(), log))
.collect();
logs.sort_by_key(|(_, log)| log.log_index);
logs
}
}

struct Log {
duration: std::time::Duration,
log_index: usize,
}

/// A struct for recording time spent in various blocks of code.
pub struct TimeRecorder {
start: chrono::DateTime<chrono::Utc>,
logs: Arc<Mutex<Vec<(String, std::time::Duration)>>>,
logs: Arc<Mutex<Logs>>,
}

impl Default for TimeRecorder {
Expand All @@ -26,7 +66,7 @@ impl TimeRecorder {
pub fn new() -> Self {
Self {
start: chrono::Utc::now(),
logs: Arc::new(Mutex::new(Vec::new())),
logs: Arc::new(Mutex::new(Logs::default())),
}
}

Expand All @@ -37,7 +77,7 @@ impl TimeRecorder {
let elapsed = now.elapsed();

if let Some(mut logs) = self.logs.try_lock() {
logs.push((description.to_owned(), elapsed));
logs.add_log(description, elapsed);
} else {
warn!("Failed to acquire logs lock, skipping timeit logging. Tried to log '{}' with '{}' elapsed.", description, format_duration(elapsed));
}
Expand Down Expand Up @@ -66,8 +106,8 @@ impl TimeRecorder {
.set_content_arrangement(ContentArrangement::Dynamic);
table.set_header(vec!["Description", "Elapsed"]);

for (description, duration) in logs.iter() {
table.add_row(vec![description, &format_duration(*duration)]);
for (description, log) in logs.sorted_logs() {
table.add_row(vec![description, &format_duration(log.duration)]);
}

table.add_row(vec![
Expand Down

0 comments on commit 51fd52e

Please sign in to comment.