Reliable monitoring of current CPU usage

I would like to track the current system-wide CPU usage on a Mac using Python.

I wrote code starting with "ps" and adds all the values ​​from the "% cpu" column.

def psColumn(colName):
    """Get a column of ps output as a list"""
    ps = subprocess.Popen(["ps", "-A", "-o", colName], stdout=subprocess.PIPE)
    (stdout, stderr) = ps.communicate()
    column = stdout.split("\n")[1:]
    column = [token.strip() for token in column if token != '']
    return column

def read(self):
    values = map(float, psColumn("%cpu"))
    return sum(values)

However, I always get high readings from 50% to 80%, probably caused by the measurement program itself. This peak CPU usage is not recorded in my Meters or other system monitoring programs. How can I get readings that are more like displaying MenuMeters? (I want to detect critical situations in which some program is chasing the processor.)

ps I tried psutil but

psutil.cpu_percent()

always returns 100%, so this is useless to me or I use it incorrectly.

+3
4

, - CPU, , ? "uptime".

, CPU . 1.0, , -. , , , . "" :

  • , , . , "ps".
  • . , - , .

.

+3

, psutil.cpu_percent().

psutil.cpu_times(), , , , . , -.

import psutil as ps

class cpu_percent:
    '''Keep track of cpu usage.'''

    def __init__(self):
        self.last = ps.cpu_times()

    def update(self):
        '''CPU usage is specific CPU time passed divided by total CPU time passed.'''

        last = self.last
        current = ps.cpu_times()

        total_time_passed = sum([current.__dict__.get(key, 0) - last.__dict__.get(key, 0) for key in current.attrs])

        #only keeping track of system and user time
        sys_time = current.system - last.system
        usr_time = current.user - last.user

        self.last = current

        if total_time_passed > 0:
            sys_percent = 100 * sys_time / total_time_passed
            usr_percent = 100 * usr_time / total_time_passed
            return sys_percent + usr_percent
        else:
            return 0
+1
>>> import psutil, time
>>> print psutil.cpu_times()
softirq=50.87; iowait=39.63; system=1130.67; idle=164171.41; user=965.15; irq=7.08; nice=0.0
>>>
>>> while 1:
...     print round(psutil.cpu_percent(), 1)
...     time.sleep(1)
...
5.4
3.2
7.3
7.1
2.5
+1
source

for psutil, when you run the .py file in the shell, the correct answer

psutil.cpu_percent(interval=1)

do not forget the argument interval = 1, otherwise it will return 0 or 100, maybe an error.

0
source

Source: https://habr.com/ru/post/1733889/


All Articles