Python函数装饰器打印函数运行时间、实现单例模式

函数装饰器的介绍:
https://www.runoob.com/w3cnote/python-func-decorators.html

1,打印函数运行时间,减少重复代码

def logit_time(func):
    """
    打印函数运行起始时间、终止时间、运行时间的装饰器
    """
    @wraps(func)
    def printFuncRunTime(*args, **kwargs):
        """
        打印函数运行时间
        """
        time1 = datetime.now()
        print(time1, f'{func.__name__} start running.')
        res = func(*args, **kwargs)
        time2 = datetime.now()
        print(time2, f'{func.__name__} done.')
        print(f'{func.__name__} total use time:', time2 - time1)
        return res
    return printFuncRunTime

使用装饰器:

@logit_time
def one_car_resample(f_name, resample_intvl, clean_data_dir):
    """
    重采样
    """
    car_vin = os.path.basename(f_name).split('.')[0].split('_')[0]
    df = pd.read_feather(f_name)

运行结果:

df_raw shape: (20712, 172)
2022-01-22 10:51:07.282897 del_not_need_col start running.
2022-01-22 10:51:07.404211 del_not_need_col done.
del_not_need_col total use time: 0:00:00.121314
2022-01-22 10:51:07.404254 extract_feature start running.
2022-01-22 10:51:07.404262 clean_data start running.
2022-01-22 10:51:11.548022 clean_data done.
clean_data total use time: 0:00:04.143760
2022-01-22 10:51:11.548087 add_basic_features start running.
2022-01-22 10:51:12.081558 add_basic_features done.
add_basic_features total use time: 0:00:00.533471

2,使用函数装饰器实现单例模式

def singleton(cls, *args, **kw):
    """
    单例模式的类装饰器:在整个项目的运行周期内只有一个实例。
    """
    instance = {}

    def _singleton():
        if cls not in instance:
            instance[cls] = cls(*args, **kw)
        return instance[cls]

    return _singleton

使用方法:

@singleton
class InitParas(object):
    """
    初始化参数配置
    """
    def __init__(self):
        self.NUM_CELLS = 28  # 电芯电压数量
        self.NUM_ETPD = 6   # 电芯温度数量
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值