Improve performance of expo by multiplying previous result
This computes the exponential by multiplying the previous result by base instead of computing it from scratch with ** each time, which seems to be about an order of magnitude faster. On my machine the following tests report around 2.63 seconds for expo_old and 0.10 for expo_new.
def expo_old(base=2, factor=1, max_value=None):
n = 0
while True:
a = factor * base ** n
if max_value is None or a < max_value:
yield a
n += 1
else:
yield max_value
def expo_new(base=2, factor=1, max_value=None):
a = 1
while True:
if max_value is None or a < max_value:
yield factor * a
a *= base
else:
yield max_value
import timeit
for e in (expo_old(), expo_new()):
print(timeit.timeit('for i in range(50): next(e)', globals={'e': e}, number=1000))
This seems good to me.
Just curious, did you run into this because you in your use case the number of retries was very high?
No, I was just browsing the code and noticed that some work was unnecessarily re-done on each loop. I think it's pretty unlikely that anyone would reach enough retries for this to actually make much of a difference, but I figured I'd submit it anyway since it's such a simple change.
Any chance this can get merged? PR has been open for over a year.
Ping?