本篇文章介绍airbus中运行时长装饰器,用于显示函数从开始运行到结束的时间,并在终端中打印出运行时长。

1. 源码

  1. import logging
  2. from datetime import datetime
  3. from functools import wraps
  4. def timeit(func):
  5. """Print cost time of `func` run."""
  6. log = logging.getLogger("Timeit")
  7. @wraps(func)
  8. def wrapper(*args, **kwargs):
  9. start = datetime.now()
  10. res = func(*args, **kwargs)
  11. end = datetime.now()
  12. cost_time = round((end - start).total_seconds(), 3)
  13. text = (f"[bold red]{func.__name__}[/] function:\n"
  14. f" Start time: {start.strftime('%Y-%m-%d %H:%M:%S')}\n"
  15. f" Cost time: {cost_time} seconds")
  16. log.info(text, extra={"markup": True})
  17. return res
  18. return wrapper

2. 使用方法

  1. import time
  2. from airbus.decorators import timeit
  3. @timeit
  4. def test_timeit():
  5. for i in range(5):
  6. time.sleep(1)
  7. test_timeit()