Last active
April 26, 2017 02:25
-
-
Save Gwill/adbf4ba3138aa064071012f0d88905b3 to your computer and use it in GitHub Desktop.
TokenBucket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from time import time | |
| class TokenBucket(object): | |
| """TokenBucket 流控算法 | |
| >>> bucket = TokenBucket(80, 0.5) | |
| >>> print bucket.consume(10) | |
| True | |
| >>> print bucket.consume(90) | |
| False | |
| """ | |
| def __init__(self, capacity, fill_rate): | |
| """fill_rate = tokens/second that the bucket will be refilled""" | |
| self.capacity = float(capacity) | |
| self._tokens = float(capacity) | |
| self.fill_rate = float(fill_rate) | |
| self.timestamp = time() | |
| def consume(self, tokens): | |
| """消费token""" | |
| if tokens <= self.tokens: | |
| self._tokens -= tokens | |
| else: | |
| return False | |
| return True | |
| def get_tokens(self): | |
| """getter""" | |
| if self._tokens < self.capacity: | |
| now = time() | |
| delta = self.fill_rate * (now - self.timestamp) | |
| self._tokens = min(self.capacity, self._tokens + delta) | |
| self.timestamp = now | |
| return self._tokens | |
| tokens = property(get_tokens) | |
| if __name__ == '__main__': | |
| from time import sleep | |
| bucket = TokenBucket(80, 1) | |
| print "tokens =", bucket.tokens | |
| print "consume(10) =", bucket.consume(10) | |
| print "consume(10) =", bucket.consume(10) | |
| sleep(1) | |
| print "tokens =", bucket.tokens | |
| sleep(1) | |
| print "tokens =", bucket.tokens | |
| print "consume(90) =", bucket.consume(90) | |
| print "tokens =", bucket.tokens |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment