import time
import datetime
class Timer:
def __init__(self):
self.prompt = '未开始计时'
self.start_time = 0
self.stop_time = 0
self.time_subtraction = 0
def __str__(self):
return self.prompt
__repr__ = __str__
def __add__(self, other):
prompt = "共运行了"
result = self.time_subtraction + other.time_subtraction
return prompt + str(result)
def start_clock(self):
self.start_time = time.clock()
print('定时器已启动')
def stop_clock(self):
self.stop_time = time.clock()
self._cacle()
print('计时器已停止')
if not self.start_time:
return print('定时器还没开启呢')
return print(self.prompt)
def _cacle(self):
self.time_subtraction = datetime.timedelta(seconds=(self.stop_time-self.start_time))
self.prompt = '计时结果为:'+str(self.time_subtraction)
if __name__ == '__main__':
t1 = Timer()
print(t1)
t1.start_clock()
time.sleep(2)
t1.stop_clock()
t2 = Timer()
t2.start_clock()
time.sleep(3)
t2.stop_clock()
print(t1+t2)
输出结果:
未开始计时
定时器已启动
计时器已停止
计时结果为:0:00:02.000031
定时器已启动
计时器已停止
计时结果为:0:00:03.000170
共运行了0:00:05.000201
来源:https://www.cnblogs.com/djflask/p/12262516.html