Skip to content

Instantly share code, notes, and snippets.

@kanazux
Created March 6, 2018 14:44
Show Gist options
  • Save kanazux/ff1a82783d41febad2049111baa313e5 to your computer and use it in GitHub Desktop.
Save kanazux/ff1a82783d41febad2049111baa313e5 to your computer and use it in GitHub Desktop.
Calculate cpu usage on linux
import time
def cpu_percent():
tmp_total = 0
tmp_idle = 0
for i in range(10):
cpu_data = !head -n1 /proc/stat
user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice = cpu_data[0].split()[1:]
diff_idle = int(idle) - tmp_idle
total_cpu_boot = sum(map(int, [user, nice, system, idle, iowait, irq, softirq, steal]))
diff_total = total_cpu_boot - tmp_total
diff_usage = 1000 * (diff_total - diff_idle) / (diff_total + 5) / 10
print diff_usage
tmp_total = total_cpu_boot
tmp_idle = int(idle)
time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment