Python -- 统计函数运行时间的 类装饰器
起因:
定义一个类装饰器函数(默认用*args, **kwargs表示不定长参数)用于统计函数或脚本的运行时间。
代码:
类装饰器的优点是可以传参:
# !usr/bin/python3
# -*- coding=utf-8 -*-
class Exectime():
def __init__(self, unit: str = 's', e_time: int = None,):
self.unit = unit
self.e_time = e_time
self.str_f = ''
def __call__(self, func):
def wrapper(*args, **kwargs):
import time as t
start_time = t.time()
res = func(*args, **kwargs)
end_time = t.time()
exec_time = self.e_time or end_time - start_time
# exec_time *= 1000
symbols = {'m': 'Minute', 'h': 'Hour', 'd': 'Day'}
sy_time = {"Minute": 60, "Hour": 3600, "Day": 86400}
try:
if symbols[self.unit]:
if symbols[self.unit] == "Minute":
exec_time = exec_time/sy_time["Minute"] if exec_time >= sy_time["Minute"] else exec_time
unit_f = "Minute"
elif symbols[self.unit] == "Hour":
exec_time = exec_time/sy_time["Minute"] if exec_time >= sy_time["Minute"] else exec_time
unit_f = "Hour"
elif symbols[self.unit] == "Day":
exec_time = exec_time/sy_time["Minute"] if exec_time >= sy_time["Minute"] else exec_time
unit_f = "Day"
except:
unit_f = "Second"
print("FuncName: {} ==> Exec: {:g} {}!\n".format(func.__name__, exec_time, unit_f))
return res
return wrapper
if __name__ == "__main__":
@Exectime()
def test():
print("This is Test() !!!")
for i in range(5000000):
i += i * i
test()
import random
# 在0-20000数字之间随机取8000个整数组成一个列表,并对其使用冒泡排序
n = [i for i in range(20000)]
arr = random.sample(n, 8000)
@Exectime()
def bubble_sort(arr):
for i in range(len(arr) - 1, 0, -1):
for j in range(i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
bubble_sort(arr)
执行效果:
C:\Users\Admin\AppData\Local\Programs\Python\Python38\python.exe D:/pythontest/99-test/111.py
This is Test() !!!
FuncName: test ==> Exec: 849.727 Second!
FuncName: bubble_sort ==> Exec: 10462 Second!
Process finished with exit code 0
其实它和 Flask 类似:
Flask中是:
from flask import Flask,render_template,url_for
# 生成Flask实例
app = Flask(__name__)
@app.route('/')
def my_echart():
# 在浏览器上渲染my_templaces.html模板
return render_template('my_template.html')
可以用下面的例子解释:
class HiDecorate:
def info(self,func):
def wrap(*args):
print ('func name:{},args:{}'.format(func.__name__,args))
func(*args)
return wrap
decorate=HiDecorate()
@decorate.info
def f(a,b):
print ('Hi Decorate')
# 运行一些,看看结果
>> f(1,2)
func name:f,args:(1, 2)
Hi Decorate
引用:
python 一个公式解决所有复杂的装饰器,https://www.bilibili.com/video/BV19U4y1d79C
小白了解Python中类装饰器,看这篇就够了 - 知乎 https://zhuanlan.zhihu.com/p/403658298
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步