Fall in love with the python series-python context manager (1): use ContextDecorator to implement function timers

The python context manager is very awesome. This experiment is because I want to practice ContextDecorator to customize a decorator

The experiment is as follows:

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)

Experimental results:

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

 

Guess you like

Origin blog.csdn.net/zhou_438/article/details/109290596