简体   繁体   English

如何使用time()倒数

[英]How to make countdown with time()

I have made this code to make a Countdown: 我编写了以下代码来进行倒计时:

import time
end = time.time() + 5.5
if time.time() == end:
    print('Time\'s up')

That didn't work. 那没用。 It wasn't an error. 这不是错误。 It didn't happened anything.Has anybody an idea? 它什么都没发生,有人有主意吗? Thanks! 谢谢!

You check time.time() again immediately after setting end , and you only check it once, so it is definitely not going to be 5.5 seconds later. 您可以在设置end之后立即再次检查time.time() ,并且只检查一次,因此肯定不会在5.5秒之后。 If you want to do this by making minimal modifications to your code: 如果要通过对代码进行最少的修改来做到这一点:

while time.time() < end:
    pass
print('Time\'s up')

you don't want to check for == in case the exact microsecond is not returned by the call to time.time(). 您不希望检查== ,以防time.time()调用未返回确切的微秒。

If you want to do this the right way, you should use time.sleep(5.5) . 如果要正确执行此操作,则应使用time.sleep(5.5)

You're comparing for equality, but that assumes that the timestamp returned is exactly the same as the original one, plus 5.5 seconds. 您正在比较是否相等,但是假设返回的时间戳与原始时间戳完全相同 ,外加5.5秒。 That won't happen unless you're very lucky. 除非您非常幸运,否则不会发生这种情况。 Additionally you're doing this check right after you've retrieved the previous time, and there is no chance that 5.5 seconds will pass between those two statements. 另外,你在做这个检查你检索以前的时间之后 ,有没有机会,目前有550秒就会这两个语句之间传递。

You can fix this by either using the appropriate way - or the naive way. 您可以使用适当的方法或天真的方法来解决此问题。

The correct way to handle this is to use time.sleep(5.5) : 解决此问题的正确方法是使用time.sleep(5.5)

import time

time.sleep(5.5)
print("Time's up!")

The naive way to implement it like in your example: 像您的示例中那样简单地实现它:

import time
end = time.time() + 5.5

while time.time() < end:
    pass

print("Time's up")

This will spin an empty loop until the requested time has passed. 这将旋转一个空循环,直到请求的时间过去。 The reason why I'm calling this naive is because your program will be stuck spending all available CPU resources while doing nothing, except for checking the clock and the current time until 5.5 seconds has passed. 我之所以这么称呼我,是因为您的程序将卡住所有可用的CPU资源,却无所事事,除了检查时钟和当前时间,直到5.5秒为止。 In the first example it tells the operating system that "Hey, wake me up in 5.5 seconds" and other processes can use the CPU in between. 在第一个示例中,它告诉操作系统“嘿,请在5.5秒内唤醒我”,其他进程可以在两者之间使用CPU。

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

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