Skip to content

Commit

Permalink
Add a speed optimization in reverse_minute()
Browse files Browse the repository at this point in the history
  • Loading branch information
cuu508 committed Nov 2, 2024
1 parent 6d8dad4 commit 87c3b6e
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion cronsim/cronsim.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,10 @@ def __init__(self, expr: str, dt: datetime, reverse: bool = False):
def tick(self, minutes: int = 1) -> None:
"""Roll self.dt in `tick_direction` by 1 or more minutes and fix timezone."""

# Tick should only receive positive values.
# Receiving a negative value or zero means a coding error.
assert minutes > 0

if self.dt.tzinfo not in (None, UTC):
as_utc = self.dt.astimezone(UTC)
as_utc += td(minutes=minutes * self.tick_direction)
Expand All @@ -208,7 +212,8 @@ def advance_minute(self) -> bool:
# An optimization for the special case where self.minutes has exactly
# one element. Instead of advancing one minute per iteration,
# make a jump from the current minute to the target minute.
delta = (next(iter(self.minutes)) - self.dt.minute) % 60
(target_minute,) = self.minutes
delta = (target_minute - self.dt.minute) % 60
self.tick(minutes=delta)

while self.dt.minute not in self.minutes:
Expand All @@ -225,6 +230,14 @@ def reverse_minute(self) -> bool:
if self.dt.minute in self.minutes:
return False

if len(self.minutes) == 1:
# An optimization for the special case where self.minutes has exactly
# one element. Instead of advancing one minute per iteration,
# make a jump from the current minute to the target minute.
(target_minute,) = self.minutes
delta = (self.dt.minute - target_minute) % 60
self.tick(minutes=delta)

while self.dt.minute not in self.minutes:
self.tick()
if self.dt.minute == 59:
Expand Down

0 comments on commit 87c3b6e

Please sign in to comment.