zoukankan      html  css  js  c++  java
  • python计算程序执行时间的装饰器使用

    1、经常被问程序执行了多久,每个函数都去写很麻烦,所以打算写个装饰器自动计算程序执行时间;推荐文档,大多数基础题都有:  https://python3-cookbook.readthedocs.io/zh_CN/latest/ 

    import  time

    def clock(func):
    def clocked(*args, **kwargs):
    start = time.time()
    result = func(*args, **kwargs)
    end = time.time()
    print(func.__name__, end - start)
    return result
    return clocked

    @clock
    def test():
    print("excute...")
    time.sleep(5)

    test()
    执行结果:

    "D:Program Filespython3.6.7python.exe" D:/pythonWorkspace/untitled4/22.py
    excute...
    test 5.000607967376709

    Process finished with exit code 0

    2、装饰器错误使用方法

    import datetime
    import time

    def clock(func):
    start = datetime.datetime.now()
    print(start)
    def clocked(*args, **kwargs):
    func(*args, **kwargs)
    end = datetime.datetime.now()
    total = (end - start).total_seconds()
    print(end)
    print("执行%s耗时:%d" %(func.__name__, total))
    return clocked

    @clock
    def test():
    print("excute...")
    time.sleep(5)

    test()
    错误的执行结果:

    "D:Program Filespython3.6.7python.exe" D:/pythonWorkspace/untitled4/55.py
    2019-08-19 10:24:29.904106
    2019-08-19 10:24:29.904106
    执行test耗时:0
    excute...

    Process finished with exit code 0

    -------------------------------------------------------------------------------------

    适用于例如:

      - 验证用户类型

    复制代码
    def user_auth(user_group):
        def wrapper(func):
            def inner(*args, **kwargs):
                if user_group == 'SVIP':
                    print('Dear SVIP')
                    res = func(*args, **kwargs)
                    return res
    
                elif user_group == 'General':
                    res = func(*args, **kwargs)
                    return res
    
                else:
                    print('Please login first!')
                    login()
    
            return inner
    
        return wrapper
    
    
    @user_auth(user_group='SVIP')
    def welcome():
        print('Welcome to the index')
  • 相关阅读:
    关于VS中更改栈和堆空间的大小
    BS模式的模型结构详解
    友情链接
    [ThinkPHP] 比较标签 neq&nheq 与 PHP 中的 != 与 !== 出现的问题
    [个人思考] 裸泳的问题
    [label][Chrome-Extension] How to start Chrome Extension's development
    [label][OS] 制作 U 盘安装 Windows 7
    [label][Google-Developers] Your First Multi Screen Site
    Min Stack
    Implement Stack using Queues
  • 原文地址:https://www.cnblogs.com/harryTree/p/11375604.html
Copyright © 2011-2022 走看看