爱上python系列------python上下文管理器(一):利用ContextDecorator实现函数计时器

python上下文管理器是很牛的存在,这个实验是因为自己想练一下ContextDecorator进行自定义一个装饰器

实验如下:

from contextlib import ContextDecorator
import  time
import math

#自定义一个装饰器
class timer(ContextDecorator):
    def __enter__(self):
        self.start=time.time()
    
    def __exit__(self,*exc):
        print('the function spend  time is',time.time()-self.start)
        
#函数1
@timer()
def create_list(x):
    return [i for i in range(x)]
#函数2
@timer()
def cal_sin(x):
    return math.sin(math.sin(math.sin(x)))
    
#开始测试
create_list(10000)
cal_sin(2)
cal_sin(3)

实验结果:

the function spend  time is 0.0002276897430419922
the function spend  time is 2.6226043701171875e-06
the function spend  time is 1.6689300537109375e-06
0.14018878179601915

猜你喜欢

转载自blog.csdn.net/zhou_438/article/details/109290596