#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName :MyTimer.py
# @Time :2023/8/27 13:57
# @Author :Jason Zhang
import time
import math
class Timer:
# 定义开始时间
def __enter__(self):
self.start = time.perf_counter()
return self
# 定义结束时间
def __exit__(self, exc_type, exc_val, exc_tb):
self.stop = time.perf_counter()
times = self.stop - self.start
print(f"times = {math.floor(times)} s")
if __name__ == "__main__":
# 测试代码
for i in range(1,11):
with Timer():
time.sleep(i)
times = 1 s
times = 2 s
times = 3 s
times = 4 s
times = 5 s
times = 6 s
times = 7 s
times = 8 s
times = 9 s
times = 10 s