Python全栈工程师

25.4-时间窗口函数实现

2019-10-21  本文已影响0人  BeautifulSoulpy

如果人生面对的最大苦难只是死亡,那还有什么可以害怕的呢?人生中没有解决不了的事,也没有无法面对的事。

滑动窗口

时间窗口分析

概念:很多数据,例如日志,都是和时间相关的,都是按照时间顺序产生的。产生的数据分析的时候,要按照时间求值;
interval 表示每一次求值的时间间隔
width 时间窗口宽度,指的一次求值的时间窗口宽度

当 width > interval
当 width = interval

当 width < interval 数据求值没有重叠

时序数据

运维环境中,日志、监控等产生的数据都是与实践相关的数据,按照时间先后产生并记录下来的数据,索引一般按照时间对数据进行分析;


窗口函数实现

攒一个数据,实现多少秒处理一次;

# 生成器;

import random #产生随机数;
import time  # 休息一会
import datetime # 时间

def source(seconds=1):
    while True:
        yield {'datetime':datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8))),'value':random.randint(1,100)}
        time.sleep(seconds)
               
s = source()
# collecting date
items = [next(s) for _ in range(3)]
print(items)

def avg_handler(iterable):
    return sum(map(lambda item:item['value'],iterable)) / len(iterable)

ret = avg_handler(items)
print('{:.2f}'.format(ret))
#--------------------------------------------------------------------
[{'datetime': datetime.datetime(2019, 10, 21, 20, 42, 31, 313003, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800))), 'value': 30}, {'datetime': datetime.datetime(2019, 10, 21, 20, 42, 32, 313114, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800))), 'value': 87}, {'datetime': datetime.datetime(2019, 10, 21, 20, 42, 33, 313352, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800))), 'value': 21}]
46.00


# 窗口函数实现;
def window(iterator,handler,width:int,interval:int):
    buf = []
    start =datetime.datetime.strptime('19700101 00:00:01 +0800','%Y%m%d %H:%M:%S %z')
    current =datetime.datetime.strptime('19700101 00:00:01 +0800','%Y%m%d %H:%M:%S %z')
    delta = width - interval
    
    while True:
        data = next(iterator)
        if data:
            buf.append(data)
            current =data['datetime']
        print(current,start)
        
        if (current - start).total_seconds() > interval:
            print('~~~~~~~~~~~~~')
            ret = handler(buf)
            print('{:.2f}'.format(ret))
            start = current
            
            # clean old_date
            buf = [x for x in buf if x['datetime'] > current - dalta ]
            
window(s,avg_handler,10,5)    
# ------------------------------------------------------------------------












上一篇下一篇

猜你喜欢

热点阅读