等待使用while的功能

时间:2017-01-01 09:32:06

标签: python python-2.x

我刚写了一个看起来像这样的函数:

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循环中应该有什么东西吗?

2 个答案:

答案 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