Python:长时间运行的进程的传递或睡眠? [英] Python: Pass or Sleep for long running processes?

查看:51
本文介绍了Python:长时间运行的进程的传递或睡眠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个队列处理应用程序,它使用线程来等待和响应要传送到应用程序的队列消息.对于应用程序的主要部分,它只需要保持活动状态.对于像这样的代码示例:

<前>为真:经过

<前>为真:时间.睡眠(1)

哪个对系统的影响最小?什么都不做,但保持 python 应用程序运行的首选方法是什么?

解决方案

我认为 time.sleep() 对系统的开销会更少.使用 pass 将导致循环立即重新评估并锁定 CPU,而使用 time.sleep 将允许暂停执行.

编辑:只是为了证明这一点,如果您启动 python 解释器并运行:

<预><代码>>>>为真:... 经过...

您可以看到 Python 立即开始消耗 90-100% 的 CPU,而:

<预><代码>>>>导入时间>>>为真:... time.sleep(1)...

甚至几乎没有在活动监视器上注册(此处使用 OS X,但对于每个平台都应该相同).

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?

解决方案

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

这篇关于Python:长时间运行的进程的传递或睡眠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆