|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
代码:
import time as t
class Timer():
def __init__(self):
self.prompt = '未计时!'
self.lasted = []
self.begin1 = 0 #1指精确到毫秒微秒。。。
self.end1 = 0
self.begin2 = 0 #2指精确到秒,localtime的精确度
self.end2 = 0
self.last = 0
self.unit = ['年','月','天','小时','分钟','秒']
self.united = [12,31,23,59,61]
def start(self):
if self.begin1 is not 0 and not self.end1:
print('计时未停止,请先运行stop结束计时')
else:
self.begin1 = t.time()
self.begin2 = t.gmtime(self.begin1)
print('开始计时...')
def stop(self):
if self.begin1 == 0:
print('未开始计时,请先运行start')
else:
self.end1 = t.time()
self.end2 = t.gmtime(self.end1)
print('停止计时...')
self._calc()
#内部方法,计算运行时间
def _calc(self):
self.lasted = []
self.prompt = '总共运行了:' #先实现数组self.lasted[],再依次把数组中的元素添加进显示
for index in range(6):
if (self.end2[index] - self.begin2[index]) < 0: #检测是否时间出现负值,若有则修改成易读的显示界面
self.lasted[index-1] -= 1
self.lasted.append(self.united[index-1] + (self.end2[index] - self.begin2[index]))
else:
self.lasted.append(self.end2[index] - self.begin2[index])
self.last = self.end1 - self.begin1
for index in range(6): #将数组中的元素添加进显示
if self.lasted[index] == 0:
pass
else:
if index == 5:
self.prompt += str(self.last) + self.unit[index]
else:
self.prompt += str(self.lasted[index]) + self.unit[index]
#重写魔法方法,可直接输出时间
def __str__(self):
return self.prompt
__repr__ = __str__ #把repr直写成和str一样的
def __add__(self,other):
prompt = '相加的和是:'
total1 = self.last + other.last
total2 = t.gmtime(total1)
total3 = []
total4 = [1970,1,1,0,0,0]
for index in range(6):
total3.append(total2[index])
total5 = list(map(lambda x:x[0] - x[1] , zip(total3,total4)))
for index in range(6):
if total5[index]:
if index == 5:
prompt += str(total1 % 10) + self.unit[index]
else:
prompt += str(total5[index]) + self.unit[index]
else:
pass
return print(prompt)
结果:
>>> a=Timer()
>>> a.start()
开始计时...
>>> a.stop()
停止计时...
>>> a
总共运行了:5.423726797103882秒
>>> b=Timer()
>>> b.start()
开始计时...
>>> b.stop()
停止计时...
>>> b
总共运行了:3.464120388031006秒
>>> a+b
相加的和是:8.887847185134888秒 |
|