记录过去分钟事件的最有效方法

时间:2019-06-06 05:24:55

标签: python time

我需要一个过去X MINUTES发生的特定事件的实时计数器。

下面的伪代码完成了我想做的事情,但是效率很低。如果我将WINDOW设置为10分钟(600秒),并且发生了很多事件,那么下面的代码将变得难以运行!

import time
import random

WINDOW = 20 #time, in seconds, for which we want to sum events before they expire

event = list()

while True:
    #REMOVE FROM THE `event` list the elements more than 20 seconds old
    event = [i for i in event if i+WINDOW>time.time()]

    # Randomly make events happen
    if random.randint(1,100)<50:
        event.append((time.time()))
    time.sleep(.5)

    #Once every 10 seconds, print on screen the number of events that happened in the past 20 seconds
    if round(time.time()) % 10 ==0:
        print(f'We have {len(event)} events in the past {WINDOW} seconds')
        time.sleep(1)

1 个答案:

答案 0 :(得分:1)

尝试反向迭代并在发现第一个旧事件时剪切列表:

tim=time.time()  # called only once
for idx in range(len(events)-1,-1,-1):
    if events[idx]+WINDOW<= tim:
        events[:idx+1]=""
        break