Skip to content

Instantly share code, notes, and snippets.

@hatkidchan
Created April 30, 2022 22:46
Show Gist options
  • Save hatkidchan/dfcf86e6d1f6e74097fb04a5bceb8a31 to your computer and use it in GitHub Desktop.
Save hatkidchan/dfcf86e6d1f6e74097fb04a5bceb8a31 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
from time import sleep
with open("/proc/stat", "r") as fh:
last_total, last_busy = None, None
while True:
fh.seek(0)
for line in fh:
if line.startswith('cpu '):
parts = list(map(int, line.split()[1:]))
user, nice, system, idle, iowait, irq, *_ = parts
total = user + nice + system + idle + iowait + irq
busy = total - idle - iowait
if last_total is not None and last_busy is not None:
diff_total = total - last_total
diff_busy = busy - last_busy
usage = diff_busy / diff_total
print('%7.3f%%' % (100 * usage))
last_total, last_busy = total, busy
sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment