我有一个接受时间序列数据的python服务器。现在我需要计算最后一分钟的平均流量,输出大约90个样本/分钟。我目前正在使用python列表来保存所有时间戳,并使用了一种非常糟糕的方法(在我看来)来计算时间戳。代码大致如下:class TrafficCalculator(object):
timestamps = []
def run():
while True:
# this gets one record of traffic
data = self.accept_data()
# get record's timestamp
timestamp = data.timestamp
# add to list
self.timestamps.append(timestamp)
# get the time one minute ago
minute_ago = timestamp - datetime.timedelta(minutes=1)
# find out the first index of the timestamp in the past that's within 1 minute
for i, t in enumerate(self.timestamp):
if t > minute_ago:
break
# see how many records are within last minute
result = len(self.timestamp[i:])
# throw away the earlier data
self.timestamp = self.timestamp[i:]
正如你所看到的,我必须对每一张唱片都这么做,如果我的流量变得很紧张,性能就会很糟糕。在
有没有更好的数据结构或算法可以让它更高效?更进一步,我如何编写一个测试来验证我的算法?谢谢!在