|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 yjptx121 于 2020-3-22 22:31 编辑
先附代码:
- import time as t
- class MyTimes():
- def __init__(self):
- self.lasted = 0.00
- self.begin = 0
- self.end = 0
- self.prompt = '未开始计时'
- self.default_time = t.perf_counter()
- def __str__(self):
- return self.prompt
- __repr__ = __str__ # 返回字符串时会先调用 repr ,然后查找 __str__ , 最后会找到self.prompt
- def __add__(self, other):
- result = self.lasted + other.lasted
- prompt = '总共运行了' + str(round(result, 2)) + '秒'
- return prompt # 返回字符串prompt
- def set_timer(self, timer): # 默认计时器
- if timer == 't.perf_counter()':
- self.default_time = t.perf_counter()
- if timer == 't.process_time()':
- self.default_time = t.process_time()
- else:
- print('输入无效!,请输入"t.perf_counter() 或 t.process_time"')
- # 开始计时
- def start(self):
- self.begin = self.default_time # 返回计时器的精准时间
- self.prompt = '请先调用stop()停止计时!'
- print('开始计时!')
- print(self.begin)
- # 计时停止
- [color=Red]def stop(self):
- if not self.begin:
- print('请先调用start()开始计时!')
- else:
- self.end = self.default_time
- self._calc() # 在结束计时的同时会调用函数_cale()
- print('结束计时!')
- print(self.end)[/color]
- [/color]
- # 计算两次时间差
- def _calc(self):
- self.lasted = self.end - self.begin
- self.prompt = '总共运行了' + str(round(self.lasted, 2)) + '秒'
- self.begin = 0
- self.end = 0
- t1 = MyTimes()
- t1.start()
- t.sleep(1)
- t1.stop()
- print(t1)
复制代码
运行结果:
- 开始计时!
- 0.047633307
- 结束计时!
- 0
- 总共运行了0.0秒
复制代码
在调用stop()的时候,一直为0,就算不用默认参数,直接调用t.perf_count()一样也是0,不知道问题出在哪了,求指点
- import time as t
- class MyTimes:
- def __init__(self):
- self.lasted = 0.00
- self.begin = 0
- self.end = 0
- self.prompt = '未开始计时'
- self.default_time = t.perf_counter # 更改
- def __str__(self):
- return self.prompt
- __repr__ = __str__ # 返回字符串时会先调用 repr ,然后查找 __str__ , 最后会找到 self.prompt
- def __add__(self, other):
- result = self.lasted + other.lasted
- prompt = '总共运行了' + str(round(result, 2)) + '秒'
- return prompt # 返回字符串 prompt
- def set_timer(self, timer): # 默认计时器
- if timer == 't.perf_counter()':
- self.default_time = t.perf_counter # 更改
- if timer == 't.process_time()':
- self.default_time = t.process_time # 更改
- else:
- print('输入无效!,请输入"t.perf_counter() 或 t.process_time"')
- # 开始计时
- def start(self):
- self.begin = self.default_time() # 更改
- self.prompt = '请先调用stop()停止计时!'
- print('开始计时!')
- print(self.begin)
- # 计时停止
- def stop(self):
- if not self.begin:
- print('请先调用start()开始计时!')
- else:
- self.end = self.default_time() # 更改
- self._calc() # 在结束计时的同时会调用函数 _calc()
- print('结束计时!')
- print(self.end)
- # 计算两次时间差
- def _calc(self):
- self.lasted = self.end - self.begin
- self.prompt = '总共运行了' + str(round(self.lasted, 2)) + '秒'
- self.begin = 0
- self.end = 0
- t1 = MyTimes()
- t1.start()
- t.sleep(1)
- t1.stop()
- print(t1)
复制代码
|
|