简体   繁体   English

在python中使用sleep做一个计时器。 如何计算时间?

[英]Make a timer using sleep in python. How to account for computation time?

I'm trying to make a simple timer which prints the time remaining every second. 我正在尝试制作一个简单的计时器,该计时器每秒打印剩余时间。

for k in range(100):
    print(100-k)
    t.sleep(1)
#output
#100
#99
#98
#...
#1

However, this will take slightly longer than 100 seconds, because there will be a delay added when print() is used. 但是,这将花费超过100秒的时间,因为使用print()时会增加延迟。 For long periods, this is slightly noticeable. 长期来看,这是比较明显的。 Is there a way to account for this, and accurately display the time every second? 有没有办法解决这个问题,并准确地每秒显示时间? I know I could just sleep(100) , but this wouldn't let the time left be printed. 我知道我可以只sleep(100) ,但这不会让剩下的时间被打印出来。

import time
start_time=time.time()
for k in range(25):
    print(25-k)
    time.sleep(1)
print("it took  "+str(float(time.time()-start_time)*1000)+" Milliseconds")

the output with print is: it took 26412.75382041931 Milliseconds 打印的输出是: it took 26412.75382041931 Milliseconds

the output without print : it took 25053.035020828247 Milliseconds 无打印输出: it took 25053.035020828247 Milliseconds

it should have been just 25000 milliseconds but it is not 应该只有25000毫秒,但不是

printing will take time, even reading the code takes time point is don't expect accurate timing with time.sleep() !!! 打印将花费时间,即使阅读代码也需要时间点,也不要指望time.sleep()的准确时间!

You can use time.time() to measure elapsed time. 您可以使用time.time()来测量经过的时间。

import time
start_time = time.time()

for k in range(100):
    # k seconds SHOULD be elapsed at this point
    print(100 - k)
    slept_time = time.time() - start_time
    time.sleep(1 + k-slept_time)

Using time.sleep will never give you the accurate time for your timer, since the time it takes is the one second sleep time + printing time, you can use threading.Timer to get more accurate results. 使用time.sleep永远不会给您准确的计时器时间,因为它花费的时间是一秒钟的睡眠时间+打印时间,所以您可以使用threading.Timer来获得更准确的结果。 https://repl.it/Hwkt : https://repl.it/Hwkt

import threading, time

start_time=time.time()
def count_loop(counter):
  if counter <= 0: 
    print("it took  "+str(float(time.time()-start_time)*1000)+" Milliseconds")
    return

  threading.Timer(1.0, count_loop, args=[counter-1]).start()
  print(counter)      

count_loop(100)

This is still not accurate, but with only very minimum offset, only 45 ms. 这仍然不准确,但是只有非常小的偏移,只有45 ms。 However, when using time.sleep from legendisback's example, there is apparently 81 ms delay. 然而,当使用time.sleep从legendisback的例子,显然有81毫秒的延迟。 https://repl.it/HwlK https://repl.it/HwlK

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM