"""
Python 上下文管理器实现
"""
import time
class Time():
"""
上下文管理器必须实现以下三个函数
"""
def __init__(self):
# 记录执行时间
self.all_time = 0
def __enter__(self):
# with Time() 自动调用 记录开始时间,并返回self
self.start = time.perf_counter()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# with 结束前调用自动关闭 记录结束时间,计算执行时时间
self.end = time.perf_counter()
self.all_time = self.end-self.start
with Time() as timer:
num = []
for i in range(1000000):
print(i)
num.append(i)
# 获取执行时间
print(timer.all_time)