My 9 Line of Python code is using 100% of My CPU

好久不见. 提交于 2019-12-11 22:08:02

问题


I have a python script (test.py) that need to be restarted every 10 - 15 minutes using below code :

import subprocess,time
WAIT=700
file_name = ("test.py")
while True:
    process=subprocess.Popen("python "+ file_name)
    now=time.time()
    while time.time() - now < WAIT:
        pass
    process.kill()

But is taking 100% of my CPU . What can be wrong ? if i run test.py only everything is normal .


回答1:


You should use the .sleep function, which won't use a cpu intensive while-loop:

import subprocess,time
WAIT=700
file_name = ("test.py")
while True:
    process=subprocess.Popen("python "+ file_name)
    time.sleep(WAIT)
    process.kill()



回答2:


The problems comes from this part of the code

while time.time() - now < WAIT:
    pass

python spent all CPU time to execute this loop as fast as the CPU allows it (so possibly million of time per second).

You need put a sleep the process a before continuing in the loop

while time.time() - now < WAIT:
    time.sleep(1)

This way the process will sleep 1 second and will execute the loop again, so the CPU will be idling. You can change the 1 to 10, 20 or even WAIT if you want to sleep 700 seconds.



来源:https://stackoverflow.com/questions/51683493/my-9-line-of-python-code-is-using-100-of-my-cpu

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!