python进程占用100%的CPU [英] python process takes 100% CPU
问题描述
我正在尝试运行python应用程序并根据指定的间隔执行操作.下面的代码不断消耗100%的CPU.
I am trying to run python application and execute actions based on specified interval. Below code is consuming constantly 100% of 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()
我希望避免使进程陷入休眠状态,因为在不同的时间间隔内将有更多的动作要执行.
I would like to avoid putting process to sleep as there will be more actions to execute at various intervals.
请告知
推荐答案
If you know when the next run will be, you can simply use 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 这样:
If you want other threads to be able to interrupt you, use an event like this:
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()
来唤醒您的线程.
Another thread can now call interruptEvent.set()
to wake up yours.
在许多情况下,您还需要使用锁定以避免对共享数据竞赛条件.请确保在按住锁的同时清除事件.
In many cases, you will also want to use a Lock to avoid race conditions on shared data. Make sure to clear the event while you hold the lock.
您还应该知道,在cpython下,只有一个线程可以执行Python代码.因此,如果您的程序在多个线程上受CPU限制,并且您正在使用cpython或pypy,则应将threading
替换为 multiprocessing
.
You should also be aware that under cpython, only one thread can execute Python code. Therefore, if your program is CPU-bound over multiple threads and you're using cpython or pypy, you should substitute threading
with multiprocessing
.
这篇关于python进程占用100%的CPU的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!