自定义计时器#
为了方便管理日志,可以:
import logging
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(name)s %(levelname)s @%(funcName)s: %(message)s")
小技巧
如果想要保存日志,可以
logging.basicConfig(level=logging.DEBUG, filename="draft/main.log", filemode="w",
format="%(asctime)s %(name)s %(levelname)s @%(funcName)s: %(message)s")
创建计时器 TimerContext
实例:
from d2py import TimerContext
# 创建计时器实例
timer = TimerContext("平方函数")
timer
TimerContext(name='平方函数')
定义函数:
@timer
def square(x):
return x**2
运行调用函数二次观察计时器的信息:
square(2)
2022-11-05 22:25:53,492 root DEBUG @__enter__: Entering 平方函数.
2022-11-05 22:25:53,494 root DEBUG @__exit__: Run time: 0.004053116 ms.
2022-11-05 22:25:53,495 root DEBUG @__exit__: Exiting 平方函数.
4
square(3)
2022-11-05 22:25:53,566 root DEBUG @__enter__: Entering 平方函数.
2022-11-05 22:25:53,567 root DEBUG @__exit__: Run time: 0.004529953 ms.
2022-11-05 22:25:53,568 root DEBUG @__exit__: Exiting 平方函数.
9
查看计时器记录的运行时间:
timer.times
[0.0040531158447265625, 0.0045299530029296875]
重置计时器,以备开始新的工作:
timer.reset()
timer.times
[]
统计运行时间#
也可以对同一函数调用多次统计平均运行时间:
timer.reset()
for k in range(3):
square(142857)
2022-11-05 22:25:53,869 root DEBUG @__enter__: Entering 平方函数.
2022-11-05 22:25:53,871 root DEBUG @__exit__: Run time: 0.004529953 ms.
2022-11-05 22:25:53,872 root DEBUG @__exit__: Exiting 平方函数.
2022-11-05 22:25:53,872 root DEBUG @__enter__: Entering 平方函数.
2022-11-05 22:25:53,873 root DEBUG @__exit__: Run time: 0.002384186 ms.
2022-11-05 22:25:53,874 root DEBUG @__exit__: Exiting 平方函数.
2022-11-05 22:25:53,875 root DEBUG @__enter__: Entering 平方函数.
2022-11-05 22:25:53,875 root DEBUG @__exit__: Run time: 0.002861023 ms.
2022-11-05 22:25:53,876 root DEBUG @__exit__: Exiting 平方函数.
查看平均运行时间:
timer.avg()
0.003258387247721354
查看运行次数:
len(timer)
3
查看累积运行时间:
timer.cumsum()
[0.0045299530029296875, 0.0069141387939453125, 0.009775161743164062]
查看总运行时间:
timer.sum()
0.009775161743164062
可以使用普通的 Python 函数验证计时器的正确性:
def square(x):
return x**2
%%timeit
square(142857)
306 ns ± 2.73 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
当然也可以这样:
with TimerContext("计时器") as cm:
for _ in range(1000000):
square(142857)
2022-11-05 23:10:29,443 root DEBUG @__enter__: Entering 计时器.
2022-11-05 23:10:29,823 root DEBUG @__exit__: Run time: 377.9917 ms.
2022-11-05 23:10:29,826 root DEBUG @__exit__: Exiting 计时器.