while循环定时器到小数点后两位错误

while loop timer to two decimal places errors

如何将输出保留到小数点后两位

无小数位:

 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 位小数结束

尝试time.sleep(.01 - timer() % .01),用timer()锁定睡眠。尽管如果 time.sleep()timer() 不支持 10 毫秒粒度,这将无济于事。它还可能取决于 Python 解释器如何在线程(GIL acquire/release)和 OS 调度器(系统有多忙以及 OS 可以在 processes/threads).

要暂停一小段时间,您可以试试忙循环:

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()

像这样使用round()函数:

print(round(60 - secs, 2))

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

顺便说一句,考虑到您的显示可能每秒仅更新 60 次,即以 16.67 毫秒为间隔,每 10 毫秒打印一次可能有点乐观。