我有一个可以接受时间序列数据的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:]
如你所见,我必须对每条记录都这样做,如果我的流量变得很大,性能就会很差。
有没有更好的数据结构或算法可以让这个过程更高效?甚至更进一步,怎么编写测试来验证我的算法?谢谢!