栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python -- 函数执行时间类装饰器

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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:UsersAdminAppDataLocalProgramsPythonPython38python.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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1030338.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号