Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimized wait generators. #204

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 18 additions & 19 deletions backoff/_wait_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,19 @@ def expo(
"""
# Advance past initial .send() call
yield # type: ignore[misc]
n = 0

a = factor
while max_value is None or a < max_value:
yield a
a *= base
while True:
a = factor * base ** n
if max_value is None or a < max_value:
yield a
n += 1
else:
yield max_value
yield max_value


def decay(
initial_value: float = 1,
decay_factor: float = 1,
min_value: Optional[float] = None
min_value: float = 0
) -> Generator[float, Any, None]:

"""Generator for exponential decay[1]:
Expand All @@ -51,14 +50,15 @@ def decay(
"""
# Advance past initial .send() call
yield # type: ignore[misc]

t = 0
while True:
a = initial_value
while a > min_value:
yield a
t += 1
a = initial_value * math.e ** (-t * decay_factor)
if min_value is None or a > min_value:
yield a
t += 1
else:
yield min_value
while True:
yield min_value
Comment on lines 54 to +61
Copy link

@yxtay yxtay Dec 22, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Following what's done in expo to remove use of **.

Suggested change
t = 0
while True:
a = initial_value
while a > min_value:
yield a
t += 1
a = initial_value * math.e ** (-t * decay_factor)
if min_value is None or a > min_value:
yield a
t += 1
else:
yield min_value
while True:
yield min_value
a = initial_value
while a > min_value:
yield a
a /= math.exp(decay_factor)
while True:
yield min_value

Alternatively for line 57.

        a *= math.exp(-decay_factor)



def fibo(max_value: Optional[int] = None) -> Generator[int, None, None]:
Expand All @@ -74,12 +74,11 @@ def fibo(max_value: Optional[int] = None) -> Generator[int, None, None]:

a = 1
b = 1
while max_value is None or a < max_value:
yield a
a, b = b, a + b
while True:
if max_value is None or a < max_value:
yield a
a, b = b, a + b
else:
yield max_value
yield max_value


def constant(
Expand Down