while循环计时器到两位小数错误

时间:2015-02-07 19:53:16

标签: timer python-3.4

如何将输出保持在两位小数

没有小数位:

 import time
 print ("60 SECOND TIMER")
 run = input('click ENTER to run')
 secs=0
 while secs < 60:
      print(60 - secs)
      time.sleep(1)
      secs = secs+1

两位小数:

 import time
 print ("60 SECOND TIMER")
 run = input('click ENTER to run')
 secs=0
 while secs < 60:
      print(60 - secs)
      time.sleep(0.01)
      secs = secs+0.01

快速注意:两个小数位开始疯狂(最后有8或9个小数位

2 个答案:

答案 0 :(得分:0)

尝试time.sleep(.01 - timer() % .01),使用timer()锁定睡眠状态。虽然time.sleep()timer()不支持10毫秒粒度,但它不会有帮助。它还可能取决于Python解释器如何在线程(GIL获取/释放)和OS调度程序之间切换(系统有多忙以及OS可以在进程/线程之间切换的速度)。

要暂停一段时间,您可以尝试使用繁忙的循环:

from time import monotonic as timer

deadline = timer() + .01
while timer() < deadline:
    pass

例如,使用time.sleep()每隔10分钟做一次可能会失败:

import time
from time import monotonic as timer

now = timer()
deadline = now + 60 # a minute
while now < deadline: # do something until the deadline
     time.sleep(.01 - timer() % .01) # sleep until 10ms boundary
     now = timer()
     print("%.06f" % (deadline - now,))

但基于繁忙循环的解决方案应该更精确:

import time
from time import monotonic as timer

dt = .01 # 10ms
time.sleep(dt - timer() % dt)  
deadline = now = timer()    
outer_deadline = now + 60 # a minute
while now < outer_deadline: # do something until the deadline
     print("%.06f" % (outer_deadline - now,))

     # pause until the next 10ms boundary
     deadline += dt
     while now < deadline:
         now = timer()

答案 1 :(得分:0)

使用round()功能,如下所示:

print(round(60 - secs, 2))

将剩余时间输出到两位小数。

顺便提一下,考虑到您的显示器可能每秒更新60次,即间隔为16.67 ms,每10 ms打印一次可能会有点乐观。