class LeakyBucket:
'''
漏桶算法:入
水流入桶速率恒定,当桶中已满,则不能入桶
'''
def __init__(self, rate, volume):
'''
rate:入桶速率
volume: 最大容积
current:桶中现有水流
times:计时
'''
self.rate = rate
self.volume = volume
self.current = 0
self.times = int(time.time())
def insert_num(self, water_mount):
# 从上次发送到这次发送,新进入的水流数量
increase = self.rate*int(time.time())-self.times
# 桶中当前水流数量,因为不能超过桶的容积,所以取较小值
self.current = min(self.current + increase, self.volume)
# 桶中剩余容积
left_num = self.volume - self.current
# 如果所需空间超过剩余容积,则不能发送数据
if water_mount>left_num:
return False
self.times = time.time()
# 可以进入桶中,进入后桶中新的水流数
self.current = self.current + water_mount
return True
限流算法 - 漏桶算法(python)
猜你喜欢
转载自www.cnblogs.com/yangjunh/p/rate-LeakyBucket.html
今日推荐
周排行