backoff icon indicating copy to clipboard operation
backoff copied to clipboard

Improve performance of expo by multiplying previous result

Open whonore opened this issue 5 years ago • 4 comments

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))

whonore avatar Sep 11 '20 16:09 whonore

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?

bgreen-litl avatar Sep 15 '20 16:09 bgreen-litl

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.

whonore avatar Sep 15 '20 17:09 whonore

Any chance this can get merged? PR has been open for over a year.

gaby avatar Oct 11 '21 19:10 gaby

Ping?

whonore avatar Feb 21 '23 22:02 whonore