马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
测试题:
0.
import time as t
class MyTimer:
def __init__(self):
self.prompt = '未开始计时!'
self.begin = 0
self.end = 0
self.unit = ['年','月','天','小时','分钟','秒']
self.lasted = []
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] != 0:
prompt += (str(result[index]) + self.unit[index])
return prompt
#开始计时函数
def start(self):
self.begin = t.localtime()
self.prompt = '请调用stop()!'
print('开始计时...')
#结束计时函数
def stop(self):
if self.begin == 0:
print('请先调用start()!')
else:
self.end = t.localtime()
self.__calc()
print('停止计时...')
def __calc(self):
self.prompt = '累计时间为:'
#之前的做法
## for index in range(6):
## self.lasted.append(self.end[index] - self.begin[index])
## if self.lasted[index]:
## self.prompt += str(self.lasted[index])
## self.prompt += self.unit[index]
#把时间相减为负考虑进来
for index in range(6):
self.lasted.append(self.end[index] - self.begin[index])
#对lasted进行操作,把数据换算成正的时间
if self.lasted[5] <0:
self.lasted[5] += 60
self.lasted[4] -=1
if self.lasted[4] <0:
self.lasted[4] += 60
self.lasted[3] -=1
if self.lasted[3] <0:
self.lasted[3] += 24
self.lasted[2] -=1
if self.lasted[2] <0:
self.lasted[2] += 31
self.lasted[1] -=1
if self.lasted[1] <0:
self.lasted[1] += 12
self.lasted[0] -=1
#把时间加到Prompt
for index in range(6):
if self.lasted[index] != 0:
self.prompt += (str(self.lasted[index]) + self.unit[index])
2.
import time as t
class MyTimer:
def __init__(self,func,number = 10):
self.prompt = '未开始计时!'
self.begin = 0
self.end = 0
self.lasted = 0
self.default_timer = t.perf_counter
self.func = func
self.number = number
def __str__(self):
return self.prompt
__repr__ = __str__
def timing(self):
self.begin = self.default_timer()
for each in range(self.number):
self.func()
self.end = self.default_timer()
self.lasted = self.end - self.begin
self.prompt = ('累计时间为:%.2f' % self.lasted + '秒')
def set_timer(self,timer):
if timer == 'perf_counter':
self.default_timer = t.perf_counter
elif timer == 'process_time':
self.default_timer = t.process_time
else:
print('请输入perf_counter或者process_time')
def a():
print('i')
# 记住self好似用了全局变量.
# 注意先后顺序.
|