Reputation: 4693
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?
Upvotes: 1
Views: 1098
Reputation: 611
When your computer is running, the CPU needs to execute a lot of processes (just for the computer to work). As a CPU is exceedingly fast it can mimic to do many tasks at the same time but it doesn't really (nowadays with multiple cores CPU and mutithreading it can, but let's forget about it for now).
To mimic multiprocessing a CPU executes a part of a process during a certain amount of time then a part of an other process then go back to the first and so on.
The CPU is allow to switch to one process to another when it is not used by the process the first process, typically when the process requires some I/O (waiting for user interaction, displaying, reading the RAM or the HDD, etc).
When you do a while true
it'll loop ASAP it has finished to execute the instructions in the while
loop.
Here ASAP really means ASAP.
So no other processes would be able to do anything in between of two loops, because the CPU is continuously processing, thus the computer hangs.
When you add a sleep
in your loop, you release the CPU, allowing it to execute other processes. It doesn't matter how long the sleep
is as a casual CPU runs millions of operations in a microsecond.
So about your question, the sleep(0.1)
allows your CPU to execute millions of operations between two check_messages_stack()
call.
For more information, take a look at "CPU Scheduling".
Upvotes: 2
Reputation: 1173
sleep
like the others have said relaxes the CPU usage, but in addition if it's something like accessing network/web data the sleep is needed to not crash the host server and ban you.
Upvotes: 1
Reputation: 2520
If the function doesn't wait for anything, it would consume 100% CPU, by adding that sleep, it gives the CPU some time to execute other processes
Upvotes: 0
Reputation: 27476
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.
Upvotes: 0