I am writing an queue processing application which uses threads for waiting on and responding to queue messages to be delivered to the app. For the main part of the application, it just needs to stay active. For a code example like:
while True: pass
or
while True: time.sleep(1)
Which one will have the least impact on a system? What is the preferred way to do nothing, but keep a python app running?
The reason you'd want to use wait() here is because wait() is non-blocking, whereas time.sleep() is blocking. What this means is that when you use time.sleep() , you'll block the main thread from continuing to run while it waits for the sleep() call to end.
Use time. This will sleep for half of a second.
Let the sleeping time and awake time of python be TS and TA respectively. Since the circle is divided into four quarters out of which three is shaded and each quarter contains six hours, Sleeping time of python is three times six, which is equal to 18 hours.
I would imagine time.sleep() will have less overhead on the system. Using pass will cause the loop to immediately re-evaluate and peg the CPU, whereas using time.sleep will allow the execution to be temporarily suspended.
EDIT: just to prove the point, if you launch the python interpreter and run this:
>>> while True:
... pass
...
You can watch Python start eating up 90-100% CPU instantly, versus:
>>> import time
>>> while True:
... time.sleep(1)
...
Which barely even registers on the Activity Monitor (using OS X here but it should be the same for every platform).
Why sleep? You don't want to sleep, you want to wait for the threads to finish.
So
# store the threads you start in a your_threads list, then
for a_thread in your_threads:
a_thread.join()
See: thread.join
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With