diff options
author | Walter Purcaro <vuolter@gmail.com> | 2015-02-16 21:59:10 +0100 |
---|---|---|
committer | Walter Purcaro <vuolter@gmail.com> | 2015-02-16 21:59:10 +0100 |
commit | 8e7d14bae4d3c836f029a1235eb227380acc3f75 (patch) | |
tree | ebd0679642cccb994e70a89a106b394189cb28bc /pyload/network/Bucket.py | |
parent | Merge branch 'stable' into 0.4.10 (diff) | |
download | pyload-8e7d14bae4d3c836f029a1235eb227380acc3f75.tar.xz |
Fix plugins to work on 0.4.10
Diffstat (limited to 'pyload/network/Bucket.py')
-rw-r--r-- | pyload/network/Bucket.py | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/pyload/network/Bucket.py b/pyload/network/Bucket.py new file mode 100644 index 000000000..408a1e240 --- /dev/null +++ b/pyload/network/Bucket.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# @author: RaNaN + +from time import time +from threading import Lock + +MIN_RATE = 10240 #: 10kb minimum rate + + +class Bucket(object): + + def __init__(self): + self.rate = 0 # bytes per second, maximum targeted throughput + self.tokens = 0 + self.timestamp = time() + self.lock = Lock() + + + def __nonzero__(self): + return False if self.rate < MIN_RATE else True + + + def setRate(self, rate): + self.lock.acquire() + self.rate = int(rate) + self.lock.release() + + + def consumed(self, amount): + """ return the time the process has to sleep, after it consumed a specified amount """ + if self.rate < MIN_RATE: + return 0 #: May become unresponsive otherwise + + self.lock.acquire() + self.calc_tokens() + self.tokens -= amount + + if self.tokens < 0: + time = -self.tokens/float(self.rate) + else: + time = 0 + + self.lock.release() + return time + + + def calc_tokens(self): + if self.tokens < self.rate: + now = time() + delta = self.rate * (now - self.timestamp) + self.tokens = min(self.rate, self.tokens + delta) + self.timestamp = now |