定制计时器,能设置计时开始和结束,且能计算两个计时器运行时间之和。
(小甲鱼编程题复习总结)
这里先补充一下常见的几个time模块的用法:
time.localtime():使用它可以获取当地时间,以时间元组的方式返回。它有九个索引值(0~8)分别对应(年,月,日,时,分,秒,一年中的星期几(0代表星期一),一年中的第几天,是否为夏令时(-1代表夏令时))
time.sleep(): 推迟调用线程的运行,单位为秒,如t.sleep(5),在执行下一个语句时,停止5秒。
time.perf_count(): 返回计时器的精准时间(系统的运行时间),原理是调用时选一随机时间点A,计算与进程开始当前时间点的差值,第二次调用时,仍取A,计算与进程结束的当前时间的差值,从而得出程序运行时间。
time.process_time(): 在不考虑认为延迟time.sleep()的情况下,只计算CPU在线程上的工作时间。
两者相比较,time.perf_count()精度更高(采样频率更高),可以获得更加准确的时间差。
import time as t
class TIME:
def __init__(self):
self.unit=['年','月','天','小时','分钟','秒']
self.borrow=[1,12,31,24,60,60]
self.prompt='未开始计时!'
self.lasted=[]
self.begin=0
self.end=0
def start(self):
self.begin=t.localtime()
self.prompt='提示:请先调用stop()结束计时'
print('计时开始')
def stop(self):
if not self.begin:
print('提示:请先调用stop()结束计时')
else:
self.end=t.localtime()
self._calc()
print('计时结束')
def _calc(self):
self.lasted = []
self.prompt='总共运行了'
for index in range(6):#因为有六个索引值分别代表年月日时分秒
temp=self.end[index]-self.begin[index]
if temp<0:
i=1
while self.lasted[index-i]<1:
self.lasted[index-i]+=self.borrow[index-i]-1
self.lasted[index-i-1]-=1
i+=1
self.lasted.append(self.borrow[index]+temp)
self.lasted[index-1]-=1
else:
self.lasted.append(temp)
if self.lasted[index]:
self.prompt+=(str(self.lasted[index])+self.unit[index])
self.begin=0
self.end=0
print(self.prompt)
def __str__(self):
return self.prompt
__repr__=__str__
def __add__(self,other):
prompt='总共运行了'
result=[]
for index in range(6):
result.append(self.lasted[index]+other.lasted[index])
if result[index]:
prompt+=(str(result[index])+self.unit[index])
return prompt
>>> t1=TIME()
>>> t2=TIME()
>>> t1.start()
计时开始
>>> t2.start()
计时开始
>>> t1.stop()
总共运行了12秒
计时结束
>>> t2.stop()
总共运行了11秒
计时结束
>>> print(t1+t2)
总共运行了23秒
设置一个计时器,使之能够统计一个函数运行若干次的时间(执行的函数为test)
import time as t
class TIME:
def __init__(self,func,number=1000):#这里也可以直接为number
self.prompt = "未开始计时"
self.lasted = 0.0
self.default_timer = t.perf_counter
self.func = func
self.number = number
def __str__(self):
return self.prompt
__repr__ = __str__
def __add__(self,other):
result = self.lasted + other.lasted
prompt = "总共运行了%0.5f秒" %result
return prompt
# 内置方法,计算运行时间
def timing(self):
self.begin = self.default_timer()
for i in range(self.number):
self.func()
self.end = self.default_timer()
self.lasted = self.end - self.begin
self.prompt = "总共运行了%0.5f 秒" %self.lasted
def set_timer(self,timer):
if timer == 'process_time':
self.default_timer = t.process_time
elif timer == 'perf_counter':
self.default_timer = t.perf_counter
else:
print("输入无效")
def test():
text = 'I love carrot!'
char = 'o'
if char in text:
pass
>>> t2=TIME(test)
>>> t2.timing()
>>> print(t2)
总共运行了0.00015 秒
>>> t2=TIME(test,100000)
>>> t2.timing()
>>> print(t2)
总共运行了0.01884 秒