Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
328 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...