python令牌桶算法
生活随笔
收集整理的這篇文章主要介紹了
python令牌桶算法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
import time
class TokenBucket(object):
# rate是令牌發(fā)放速度,capacity是桶的大小
def __init__(self, rate, capacity):
self._rate = rate
self._capacity = capacity
self._current_amount = 0
self._last_consume_time = int(time.time())
# token_amount是發(fā)送數(shù)據(jù)需要的令牌數(shù)
def consume(self, token_amount):
increment = (int(time.time()) - self._last_consume_time) * self._rate # 計(jì)算從上次發(fā)送到這次發(fā)送,新發(fā)放的令牌數(shù)量
self._current_amount = min(
increment + self._current_amount, self._capacity) # 令牌數(shù)量不能超過(guò)桶的容量
if token_amount > self._current_amount: # 如果沒有足夠的令牌,則不能發(fā)送數(shù)據(jù)
return False
self._last_consume_time = int(time.time())
self._current_amount -= token_amount
return True
作者:simpleapples
鏈接:https://juejin.im/post/5ab10045518825557005db65
來(lái)源:掘金
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
總結(jié)
以上是生活随笔為你收集整理的python令牌桶算法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Java 线程池相关问题
- 下一篇: 如何修改主机名hostname