Skip to content

Commit

Permalink
improve clear() efficiency
Browse files Browse the repository at this point in the history
  • Loading branch information
deanlee committed Sep 9, 2024
1 parent b286a2f commit 85f67ee
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions selfdrive/selfdrived/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ def __init__(self):
self.events: list[int] = []
self.static_events: list[int] = []
self.event_counters = dict.fromkeys(EVENTS.keys(), 0)
self.prev_event_set: set[int] = set()

@property
def names(self) -> list[int]:
Expand All @@ -65,9 +66,20 @@ def add(self, event_name: int, static: bool=False) -> None:
bisect.insort(self.static_events, event_name)
bisect.insort(self.events, event_name)

self.event_counters[event_name] += 1

def clear(self) -> None:
self.event_counters = {k: (v + 1 if k in self.events else 0) for k, v in self.event_counters.items()}
# Get events no longer active
current_event_set = set(self.events)
events_to_clear = self.prev_event_set - current_event_set

# Reset counters for inactive events
for event_name in events_to_clear:
self.event_counters[event_name] = 0

# Reset active events and update previous set
self.events = self.static_events.copy()
self.prev_event_set = current_event_set

def contains(self, event_type: str) -> bool:
return any(event_type in EVENTS.get(e, {}) for e in self.events)
Expand All @@ -85,7 +97,7 @@ def create_alerts(self, event_types: list[str], callback_args=None):
if not isinstance(alert, Alert):
alert = alert(*callback_args)

if DT_CTRL * (self.event_counters[e] + 1) >= alert.creation_delay:
if (DT_CTRL * self.event_counters[e]) >= alert.creation_delay:
alert.alert_type = f"{EVENT_NAME[e]}/{et}"
alert.event_type = et
ret.append(alert)
Expand Down

0 comments on commit 85f67ee

Please sign in to comment.