Python: Pass or Sleep for long running processes?

前端 未结 7 1414
情书的邮戳
情书的邮戳 2020-11-30 05:10

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 applica

7条回答
  •  时光说笑
    2020-11-30 06:05

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

提交回复
热议问题