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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值