本篇文章介绍airbus
中运行时长装饰器,用于显示函数从开始运行到结束的时间,并在终端中打印出运行时长。
1. 源码
import logging
from datetime import datetime
from functools import wraps
def timeit(func):
"""Print cost time of `func` run."""
log = logging.getLogger("Timeit")
@wraps(func)
def wrapper(*args, **kwargs):
start = datetime.now()
res = func(*args, **kwargs)
end = datetime.now()
cost_time = round((end - start).total_seconds(), 3)
text = (f"[bold red]{func.__name__}[/] function:\n"
f" Start time: {start.strftime('%Y-%m-%d %H:%M:%S')}\n"
f" Cost time: {cost_time} seconds")
log.info(text, extra={"markup": True})
return res
return wrapper
2. 使用方法
import time
from airbus.decorators import timeit
@timeit
def test_timeit():
for i in range(5):
time.sleep(1)
test_timeit()