利用装饰器和上下文管理,函数执行前后增强
需求:
执行一个加函数后,统计一下耗时
装饰器
import time import datetime def logger(fn): def wraper(*args,**kwargs): start = start = datetime.datetime.now() ret = fn(*args,**kwargs) end = datetime.datetime.now() time_count = (end - start).total_seconds() print('耗时为{}'.format(time_count)) return ret return wraper @logger def add(x,y): time.sleep(2) rt = x + y print('计算结果为{}'.format(rt))
add(3,4)
上下文管理
import time import datetime class Timeit: def __init__(self,x,y): self.x = x self.y = y def __enter__(self): self.start = datetime.datetime.now() def __exit__(self,exc_type,exc_val,exc_tb): self.end = datetime.datetime.now() self.time_count = (self.end - self.start).total_seconds() print('计算结果为{}'.format(self.rt)) print('耗时为{}'.format(self.time_count)) def add(self): time.sleep(2) self.rt = self.x + self.y return self.rt a = Timeit(3,4) with a as a1: a.add()