Apaixone-se pelo gerenciador de contexto python série python (1): use ContextDecorator para implementar temporizadores de função

O gerenciador de contexto python é muito bom. Este experimento é porque eu quero praticar ContextDecorator para personalizar um decorador

O experimento é o seguinte:

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)

Resultados experimentais:

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

 

Acho que você gosta

Origin blog.csdn.net/zhou_438/article/details/109290596
Recomendado
Clasificación