python装饰器打印函数执行时间_python--装饰器--测试程序运行次数以及程序运行时间...

python的装饰器应用极其广泛,在python--学习的章节有所描述,在这里写两个常用的装饰器。

测试程序运行次数的装饰器

def run_times_outt(func):

count = 0

def run_times_inn(*args,**kwargs):

nonlocal count

count += 1

func(*args,**kwargs)

print('函数func运行次数为:{}'.format(count))

return run_times_inn

@run_times_outt

def test_func():

print('函数运行了!!!')

for i in range(10):

test_func()

运行结果:

函数运行了!!!

函数func运行次数为:1

函数运行了!!!

函数func运行次数为:2

函数运行了!!!

函数func运行次数为:3

函数运行了!!!

函数func运行次数为:4

函数运行了!!!

函数func运行次数为:5

函数运行了!!!

函数func运行次数为:6

函数运行了!!!

函数func运行次数为:7

函数运行了!!!

函数func运行次数为:8

函数运行了!!!

函数func运行次数为:9

函数运行了!!!

函数func运行次数为:10

测试函数运行时间的装饰器

import time

def run_out_time(func):

def run_in_time(*args,**kwargs):

t0 = time.time()

func(*args,**kwargs)

t1 = time.time()

print('函数运行时间为{}'.format(t1 - t0))

return run_in_time

@run_out_time

def type_test():

print('-------------type函数运行时间----------------------')

for i in range(10000):

type('人生苦短,我用python')

type_test()

运行结果:

-------------type函数运行时间----------------------

函数运行时间为0.0009984970092773438

这两个装饰器在程序测试中会经常用到。也可以联合使用。

import time

def run_times_outt(func):

count = 0

def run_times_inn(*args,**kwargs):

nonlocal count

count += 1

func(*args,**kwargs)

print('函数{}运行次数为:{}'.format(func,count))

return run_times_inn

def run_time_outt(func):

def run_time_inn(*args,**kwargs):

t = time.time()

func(*args,**kwargs)

print('程序运行时间为:{}'.format(time.time() - t))

return run_time_inn

@run_times_outt

@run_time_outt

def test_func():

for i in range(1000000):

type(i)

print('函数运行了!!!')

for i in range(10):

test_func()

输出:

函数运行了!!!

程序运行时间为:0.10501623153686523

函数.run_time_inn at 0x00000235963F7730>运行次数为:1

函数运行了!!!

程序运行时间为:0.13301825523376465

函数.run_time_inn at 0x00000235963F7730>运行次数为:2

函数运行了!!!

程序运行时间为:0.12669014930725098

函数.run_time_inn at 0x00000235963F7730>运行次数为:3

函数运行了!!!

程序运行时间为:0.11151671409606934

函数.run_time_inn at 0x00000235963F7730>运行次数为:4

函数运行了!!!

程序运行时间为:0.10951447486877441

函数.run_time_inn at 0x00000235963F7730>运行次数为:5

函数运行了!!!

程序运行时间为:0.1155393123626709

函数.run_time_inn at 0x00000235963F7730>运行次数为:6

函数运行了!!!

程序运行时间为:0.11101078987121582

函数.run_time_inn at 0x00000235963F7730>运行次数为:7

函数运行了!!!

程序运行时间为:0.10601115226745605

函数.run_time_inn at 0x00000235963F7730>运行次数为:8

函数运行了!!!

程序运行时间为:0.10701227188110352

函数.run_time_inn at 0x00000235963F7730>运行次数为:9

函数运行了!!!

程序运行时间为:0.10759115219116211

函数.run_time_inn at 0x00000235963F7730>运行次数为:10

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值