Skip to content

Instantly share code, notes, and snippets.

@petehunt
Created October 8, 2016 00:13
Show Gist options
  • Save petehunt/08c9fef5703e79ca26ceed845163dcdc to your computer and use it in GitHub Desktop.
Save petehunt/08c9fef5703e79ca26ceed845163dcdc to your computer and use it in GitHub Desktop.
import time
class Bucket(object):
def __init__(self, max_amount, refill_time, refill_amount):
self.max_amount = max_amount
self.refill_time = refill_time
self.refill_amount = refill_amount
self.reset()
def _refill_count(self):
return int(((time.time() - self.last_update) / self.refill_time))
def reset(self):
self.value = self.max_amount
self.last_update = time.time()
def get(self):
return min(
self.max_amount,
self.value + self._refill_count() * self.refill_amount
)
def reduce(self, tokens):
refill_count = self._refill_count()
self.value += refill_count * self.refill_amount
self.last_update += refill_count * self.refill_time
if self.value >= self.max_amount:
self.reset()
if tokens > self.value:
return False
self.value -= tokens
return True
@tim-seoss
Copy link

Hi,

You seem to have chosen - https://choosealicense.com/no-license/

was that intentional?

Thanks!

Tim.

@jar-o
Copy link

jar-o commented Oct 24, 2017

would help if there was an example demoing usage

b = Bucket(20, 10, 20)
print b.get()
print b.reduce(19)
print b.get()

print b.reduce(1)
print b.get()

# can't reduce because we're not past the time limit
time.sleep(5)
print b.reduce(1)

# now we can reduce again because the bucket has been filled (10 sec passed)
time.sleep(12)
print b.get()
print b.reduce(1)
print b.get()

the above yields

20
True
1
True
0
False
20
True
19

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment