Question: wait function that uses while

Question

wait function that uses while

Answers 2
Added at 2017-01-01 10:01
Tags
Question

I just wrote a function that looked like this:

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

Can anything bad come of this? Should there ideally be something inside the while loop?

Answers
nr: #1 dodano: 2017-01-01 10:01

time.sleep(seconds) seconds does just that without burning through CPU cycles. your loop keeps the CPU fully busy. i do not know for you but i consider this bad.

nr: #2 dodano: 2017-01-01 10:01

maybe putting time.sleep(1) in the while loop will require less cycles? Or

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
Source Show
◀ Wstecz