Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Pass or Sleep for long running processes?

Tags:

python

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?

like image 511
Gavin M. Roy Avatar asked Feb 09 '09 17:02

Gavin M. Roy


People also ask

Is time sleep blocking Python?

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.

How do you wait 0.5 seconds in Python?

Use time. This will sleep for half of a second.

What is the sleeping time of Python in hours?

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.


Video Answer


2 Answers

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

like image 88
Jay Avatar answered Sep 24 '22 14:09

Jay


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

like image 34
tzot Avatar answered Sep 24 '22 14:09

tzot