我刚写了一个看起来像这样的函数:
def block_for(seconds):
"""Wait at least seconds, this function should not be affected by the computer sleeping."""
end_time = datetime.datetime.now() + datetime.timedelta(seconds)
while datetime.datetime.now() < end_time:
pass
这有什么不好的吗?理想情况下,while循环中应该有什么东西吗?
答案 0 :(得分:4)
time.sleep(seconds)
秒就可以在没有烧掉CPU周期的情况下做到这一点。你的循环让CPU完全忙碌。我不知道你,但我认为这坏。
答案 1 :(得分:2)
在while循环中放置time.sleep(1)可能需要更少的周期?或
def block_for(seconds):
"""Wait at least seconds, this function should not be affected by the computer sleeping."""
end_time = datetime.datetime.now() + datetime.timedelta(seconds=seconds)
while datetime.datetime.now() < end_time - datetime.timedelta(seconds=1):
time.sleep(1)
while datetime.datetime.now() < end_time:
pass