Python psutil module using too much cpu when iterating through processes on Windows

Viewed 26

I've been trying to create a monitor to know which process is using cpu the most and the overall cpu usage I need it to be refreshing the information every second, for this I've been using psutil but when I use the next piece of code on Windows it uses up to 8% of my cpu while on Linux it uses practically nothing I think 8% is too much, Window's task manager doesn't even use 2% and it displays a lot of information, is there something i can do to lower the cpu usage?

import time
import psutil


while True:
    ini_proc_cpu_usage = []  # Stores initial cpu usage per process
    last_proc_cpu_usage = []  # Stores last cpu usage per process
    process_name = []  # Processes name
    process_index = 0  # Keeps track of index to remove non-existent processes
    # Creates new list with all the current running processes
    procs = [process for process in psutil.process_iter()]

    # First request to get overall cpu usage
    psutil.cpu_percent(0)

    # First request to get cpu usage per process
    for p in procs[:]:
        # Condition for windows platform to ignore
        # System Idle Process from processes
        if not p.name() == "System Idle Process":
            try:
                # Appends cpu usage per process
                ini_proc_cpu_usage.append(p.cpu_percent(0))
            # Exception if the process doesn't exist anymore
            except (psutil.NoSuchProcess, psutil.ZombieProcess):
                procs.remove(p)  # Removes process from list
                continue
            # Exception for access denied due to user privileges
            except psutil.AccessDenied:
                procs.remove(p)
                pass

    time.sleep(1)  # Time nedeed tu get more accurate info

    # Second request to get overall cpu usage
    last_cpu_usage = psutil.cpu_percent(0)

    # Second request to get top io process info
    for p in procs[:]:
        # Condition for windows platform to ignore
        # System Idle Process from processes
        if not p.name() == "System Idle Process":
            try:
                # Oneshot makes info request quicker
                with p.oneshot():
                    # Creates list with io information for the second time
                    last_proc_cpu_usage.append(p.cpu_percent(0))
                    process_name.append(p.name())  # Gets process name
                    process_index += 1  # Counter for getting index
            # Exception if the process doesn't exist anymore
            except (psutil.NoSuchProcess, psutil.ZombieProcess):
                procs.remove(p)  # Removes process from list
                # Removes process from ini_proc_cpu_usage as well
                ini_proc_cpu_usage.pop(process_index)
                continue
            # Exception for access denied due to user privileges
            except psutil.AccessDenied:
                procs.remove(p)
                pass

    # Gets cpu usage in percentage
    cpu_percent = str(round(last_cpu_usage))

    # Gets top process index this is useful to get process name
    top_process_index = last_proc_cpu_usage.index(max(last_proc_cpu_usage))
    # Converts average top cpu usage into percent
    top_cpu_percent = max(last_proc_cpu_usage)
    top_cpu_percent = top_cpu_percent / psutil.cpu_count()
    top_cpu_percent = f"{top_cpu_percent:.1f}"
    # Gets process name
    top_process_name = process_name[top_process_index]

    print(f"{cpu_percent}%, {top_process_name}: {top_cpu_percent}%")
1 Answers

In case someone else run into this issue I found out that just by running the script as Administrador solved it, now psutil uses almost nothing of my cpu.

Related