当前位置:首页 > python > 正文内容

python 装饰器 之打印函数执行时间

root4年前 (2021-12-31)python1234

在实际开发中 遇见很多需要排查函数执行时间定位性能瓶颈点

用装饰器获取函数执行的时间还是比较方便的

import inspect
import time

def timethis(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)
        end = time.time()
        print(inspect.getfile(func), func.__name__, end - start)
    return wrapper


装饰器的执行情况

@timethis
def test1(a):
    print("test1开始")
    print(a)
    time.sleep(1)
    print("test1结束")

def test2(a):
    print("test2开始")
    print(a)
    time.sleep(1)
    print("test3结束")


if __name__ == '__main__':
    # 有装饰器的情况下执行
    test1(10)
    
    # 下面执行情况等效于装饰器的执行
    timethis(test2)(10)


扫描二维码推送至手机访问。

版权声明:本文由一叶知秋发布,如需转载请注明出处。

本文链接:https://zhiqiu.top/?id=195

分享给朋友:

相关文章

Python eventlet 模块,Timeout() 控制子程序运行时间

pip install  eventlet #安装依赖包# -*- coding:utf-8 -*- import eventlet import time e...

cmd启动python交互模式 出现UnicodeDecodeError: 'gbk' codec can't decode byte 0x9a in position 533

这是因为在python交互模式的中输出了中文,且是个输出被记录在.python_history中删除历史记录文件C:\Users\Administrator\.python_history...

python csvw格式文件转parquet格式文件

用到的包: pandas    pyarrow    pandas pd df pd.(,,) df.()要求csv文件 要有头行一定要安装pyarro...

python 之optparse模块OptionParser

该模块让python脚本命令能够符合标准的Unix命令例程式每个命令行参数就是由参数名字符串和参数属性组成的。如 -f 或者 file 分别是长短参数名当你将所有的命令行参数都定义好了的时候,我们需要调用parse_args()方法赖际熙a...

Python的多线程并发限制

maxConnections connection_lock (maxConnections)在开启线程前执行connection_lock.acquire()线程执行结束执行connection_lock.releas...

PIL 模块处理图像的几种模式

PIL有九种不同模式: 1,L,P,RGB,RGBA,CMYK,YCbCr,I,F1、表示二值图像不黑就是白L、为灰度图像,每个像素用8个bit表示,0表示黑,255表示白,其他数字表示不同的灰度在PIL中,从模式“RGB”转换为...