Python: Pass or Sleep for long running processes?

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?


Solution 1:

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).

Solution 2:

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

Solution 3:

If you are looking for a short, zero-cpu way to loop forever until a KeyboardInterrupt, you can use:

from threading import Event

Event().wait()

Note: Due to a bug, this only works on Python 3.2+. In addition, it appears to not work on Windows. For this reason, while True: sleep(1) might be the better option.

For some background, Event objects are normally used for waiting for long running processes to complete:

def do_task():
    sleep(10)
    print('Task complete.')
    event.set()

event = Event()
Thread(do_task).start()
event.wait()

print('Continuing...')

Which prints:

Task complete.
Continuing...