Is time.sleep() more efficient than a while loop and if statement?

Viewed 83

Background

I am querying data every 'x' number of minutes & performing various calculations.

I came up with two ways of doing it. I like the first one better. The reason is if I add more in-between code that takes 'y' time to compute, it would still run every 'x' minutes. Using time.sleep, I would need to calculate 'y' time remaining in order to make sure 'x' update was always consistent.

While Loop One:

import datetime
from datetime import datetime, timedelta
import time

frequency = 10/60

first_start = True
target_time = datetime.now()

while(True):
    if(target_time < datetime.now()):
        if(first_start):
            start_time = datetime.now()
            first_start = False
        else:
            start_time = end_time
        
        end_time = start_time + timedelta(minutes=frequency)
        
        target_time = end_time + timedelta(minutes=frequency)
        
        print("Start: ", start_time)
        print("End: ", end_time)
        print("Target: ", target_time)

Or I can swap the while loop out with the following:

While Loop Two:

first_start = True
target_time = datetime.now()

while(True):
    if(first_start):
        start_time = datetime.now()
        first_start = False
    else:
        start_time = end_time

    end_time = start_time + timedelta(minutes=frequency)

    target_time = end_time + timedelta(minutes=frequency)

    print("Start: ", start_time)
    print("End: ", end_time)
    print("Target: ", target_time)
    time.sleep(frequency*60)

Isn't time.sleep() doing something very similar just in the background (while loop checking that 'x' number of seconds has been completed before returning)?

Or is it doing something more efficient?

1 Answers

Both operations are blocking. You can accheive the same by using crontab or celery beat or apscheduler without blocking your CPU

Related