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

2019-08-22 02:22发布

问题:

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.