|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
在学time模块
1、用while时
- import time as t
- class Thirdtimer():
- def __init__(self,func,times = 100000):
- self.default_timer = t.perf_counter
- self.prompt = "未开始计时!"
- self.lasted = 0.0
- self.func = func
- self.times = times
-
- def __str__(self):
- return self.prompt
- __repr__ = __str__
- #多次计时
- def __add__(self,other):
- result = self.lasted + other.lasted
- prompt = "总共运行了 %0.2f 秒" % result
- return prompt
- #启动计时器
- def timing(self):
- self.begin = self.default_timer()
- while self.times > 0:
- self.times -= 1
- self.func()
- self.end = self.default_timer()
- self.lasted = self.end - self.begin
- self.prompt = "总共运行了 %0.2f 秒" % self.lasted
- self.begin = 0
- self.end = 0
- #设置默认计时器
- def set_timer(self,timer):
- if timer == 'process_timer':
- self.default_timer = t.process_time
- elif timer == 'perf_counter':
- self.default_timer = t.perf_counter
- else:
- print('输入无效,请输入perf_counter或process_timer')
- def test():
- text = "I love Fishc.com"
- char = 'o'
- if char in text:
- pass
复制代码
2、用for时
- import time as t
- class Thirdtimer():
- def __init__(self,func,times = 100000):
- self.default_timer = t.perf_counter
- self.prompt = "未开始计时!"
- self.lasted = 0.0
- self.func = func
- self.times = times
-
- def __str__(self):
- return self.prompt
- __repr__ = __str__
- #多次计时
- def __add__(self,other):
- result = self.lasted + other.lasted
- prompt = "总共运行了 %0.2f 秒" % result
- return prompt
- #启动计时器
- def timing(self):
- self.begin = self.default_timer()
- for i in range(self.times):
- self.func()
- self.end = self.default_timer()
- self.lasted = self.end - self.begin
- self.prompt = "总共运行了 %0.2f 秒" % self.lasted
- self.begin = 0
- self.end = 0
- #设置默认计时器
- def set_timer(self,timer):
- if timer == 'process_timer':
- self.default_timer = t.process_time
- elif timer == 'perf_counter':
- self.default_timer = t.perf_counter
- else:
- print('输入无效,请输入perf_counter或process_timer')
- def test():
- text = "I love Fishc.com"
- char = 'o'
- if char in text:
- pass
复制代码 idle中,31.39是while循环,13.79是for循环,这是不是说明for比while快,因为while多了判断吗?哈哈哈,吹吹水,如果有大佬懂原理跟我说一声
- >>> t1 = Thirdtimer(test,100000000)
- >>> t1.timing()
- >>> t1
- 总共运行了 31.39 秒
- >>>
- ===================== RESTART: C:\Users\86181\Desktop\44.py ====================
- >>> t1 = Thirdtimer(test,100000000)
- >>> t1.timing()
- >>> t1
- 总共运行了 13.79 秒
复制代码
|
|