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

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

root5年前 (2021-12-31)python1833

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

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

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://www.zhiqiu.top/?id=195

分享给朋友:

相关文章

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

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

python简单的加密解密

rsa 是非对称加密公钥加密,私钥解密pip install rsaimport rsa from binascii import b2a_hex, a2b_hex class&nb...

python os 模块文件常用操作

123456import os #回去当前文件路径os.path.realpath(__file__)#获取文件是否存在os.path.exists(filepath)#获取文件大小os.path.getsize(fil...

python 的configparser 读取配置文件遇到%特殊符号

test.ini 配置文件中有mysql的密码,且密码含有“%”这个特殊符号因为%在py是转义符的含义需要对该字符转义即修改  %  为 %%用%对%进行转义...

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

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

python用requests发送模拟请求忽略https的认证,忽略警告

import warnings warnings.filterwarnings('ignore')在文件头添加忽略警告信息的输出r = requests.get('https://kyfw.12306.cn&#...