Get CPU usage and memory stats in Python.

Get CPU usage and memory stats in Python.

Geting CPU usage, memory consumption and IOstats in Python is easy when using the psutil python module.

“psutil (process and system utilities) is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network, sensors) in Python.”

Installation

Installation is super easy. Just use pip and install!

$ pip3 install psutil

Usage

import psutil
import time
while(1):
    cpu_t = psutil.cpu_times()
    mem = psutil.virtual_memory()
    print("%s,%s,%s,%s" %.
    (.
    psutil.cpu_percent() ,
    mem.used / 1000000,
    mem.total / 1000000,
    cpu_t.iowait
    ))

Will output….

0.0,237.166592,1849.638912,150.84
100.0,237.166592,1849.638912,150.84
0.0,237.166592,1849.638912,150.84
0.0,237.166592,1849.638912,150.84
0.0,237.166592,1849.638912,150.84
0.0,237.166592,1849.638912,150.84
50.0,237.166592,1849.638912,150.84
0.0,237.166592,1849.638912,150.84
0.0,237.166592,1849.638912,150.84

Leave a Reply