Search code examples
pythonloops

What is the point of adding short sleep to while true loop?


Across the internet, I've saw several examples of handling a service, which awaits for messages from clients in an endless loop, including a short sleep. Example:

while True:
    check_messages_stack()
    sleep(0.1)

What's the point of the sleep there? Is it supposed to save resources? If it does save some resources, would it be a meaningful amount?


Solution

  • sleep doesn't use CPU resources, but constantly executing check_messages_stack() might (depending what you have there) so if you don't need to do it constantly it is a good practice to give CPU some time off.