Skip to content

Commit

Permalink
Efficiently clean up expired timers in clocks (#2064)
Browse files Browse the repository at this point in the history
  • Loading branch information
twitu authored Nov 20, 2024
1 parent cbbe657 commit d52a87c
Showing 1 changed file with 24 additions and 11 deletions.
35 changes: 24 additions & 11 deletions nautilus_core/common/src/clock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,12 +155,15 @@ impl TestClock {
self.time.set_time(to_time_ns);
}

let mut events: Vec<TimeEvent> = self
.timers
.iter_mut()
.filter(|(_, timer)| !timer.is_expired())
.flat_map(|(_, timer)| timer.advance(to_time_ns))
.collect();
// Iterate and advance timers and collect events. Only retain alive timers.
let mut events: Vec<TimeEvent> = Vec::new();
self.timers.retain(|_, timer| {
timer.advance(to_time_ns).for_each(|event| {
events.push(event);
});

!timer.is_expired()
});

events.sort_by(|a, b| a.ts_event.cmp(&b.ts_event));
events
Expand All @@ -182,13 +185,14 @@ impl TestClock {

self.time.set_time(to_time_ns);

self.timers
.iter_mut()
.filter(|(_, timer)| !timer.is_expired())
.flat_map(|(_, timer)| timer.advance(to_time_ns))
.for_each(|event| {
// Iterate and advance timers and push events to heap. Only retain alive timers.
self.timers.retain(|_, timer| {
timer.advance(to_time_ns).for_each(|event| {
self.heap.push(event);
});

!timer.is_expired()
});
}

/// Matches `TimeEvent` objects with their corresponding event handlers.
Expand Down Expand Up @@ -398,6 +402,11 @@ impl LiveClock {
pub const fn get_timers(&self) -> &HashMap<Ustr, LiveTimer> {
&self.timers
}

// Clean up expired timers. Retain only live ones
fn clear_expired_timers(&mut self) {
self.timers.retain(|_, timer| !timer.is_expired());
}
}

impl Default for LiveClock {
Expand Down Expand Up @@ -510,6 +519,8 @@ impl Clock for LiveClock {
);

timer.start();

self.clear_expired_timers();
self.timers.insert(Ustr::from(name), timer);
}

Expand Down Expand Up @@ -552,6 +563,8 @@ impl Clock for LiveClock {
self.heap.clone(),
);
timer.start();

self.clear_expired_timers();
self.timers.insert(Ustr::from(name), timer);
}

Expand Down

0 comments on commit d52a87c

Please sign in to comment.