pythonresourcesnice

How to reduce CPU usage in Windows?


If I use

import os
os.nice(10)

The error is

AttributeError: 'module' object has no attribute 'nice'

nice is probably only for Linux systems, so how do I reduce the CPU resources available to my program?

It checks whether a particular process is running, and if it is not, then it executes it.

My code looks like this:

import subprocess, psutil

proc = subprocess.Popen(['flux'])
pid = proc.pid
while 1:
    if not psutil.pid_exists(pid):
        proc = subprocess.Popen(['flux'])
        pid = proc.pid

I would like it to use the minimum possible resources.


Solution

  • You're busywaiting; that loop will execute as fast as it can. Nice'ing the process (even if that API existed on Windows) would not help. It would just let other processes go first if they wanted to use the CPU, but your program would still get to eat up all the remaining cycles.

    A simple way to fix this is to sleep a bit between checks:

    import time
    
    ...
    
    while 1:
        time.sleep(1)
        if not psutil.pid_exists(pid):
            proc = subprocess.Popen(['flux'])
            pid = proc.pid
    

    But a better way is to just block until the program finishes. You can do that like so:

    import subprocess
    
    while True:
        subprocess.call(['flux'])
    

    Since subprocess.call blocks until the process exits, your code won't spend any cycles during this time.