我正在尝试运行 python 应用程序并根据指定的时间间隔执行操作。下面的代码持续消耗 100% 的 CPU。
def action_print():
print "hello there"
interval = 5
next_run = 0
while True:
while next_run > time.time():
pass
next_run = time.time() + interval
action_print()
我想避免让进程进入睡眠状态,因为在不同的时间间隔会执行更多的操作。
请指教
如果您知道下次运行的时间,您可以简单地使用time.sleep http://docs.python.org/library/time.html#time.sleep:
import time
interval = 5
next_run = 0
while True:
time.sleep(max(0, next_run - time.time()))
next_run = time.time() + interval
action_print()
如果您希望其他线程能够中断您,请使用event http://docs.python.org/library/threading.html#event-objects像这样:
import time,threading
interval = 5
next_run = 0
interruptEvent = threading.Event()
while True:
interruptEvent.wait(max(0, next_run - time.time()))
interruptEvent.clear()
next_run = time.time() + interval
action_print()
另一个线程现在可以调用interruptEvent.set()
唤醒你的。
在许多情况下,您还需要使用Lock http://docs.python.org/library/threading.html#lock-objects避免竞争条件 http://en.wikipedia.org/wiki/Race_condition关于共享数据。确保在锁定时清除事件。
你还应该知道,在cpython下,只有一个线程可以执行Python代码。因此,如果您的程序在多个线程上受 CPU 限制,并且您使用的是 cpython 或 pypy,则应该替换threading
with multiprocessing http://docs.python.org/library/multiprocessing.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)