Skip to content

Instantly share code, notes, and snippets.

@markuskont
Created November 23, 2018 06:23
Show Gist options
  • Save markuskont/391b122ff89e3193b179424b6a8c5559 to your computer and use it in GitHub Desktop.
Save markuskont/391b122ff89e3193b179424b6a8c5559 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import glob
RED = "\033[1;31m"
BLUE = "\033[1;34m"
CYAN = "\033[1;36m"
GREEN = "\033[0;32m"
RESET = "\033[0;0m"
BOLD = "\033[;1m"
REVERSE = "\033[;7m"
LIGHT_PURPLE = '\033[94m'
CRED = '\033[91m'
CEND = '\033[0m'
# Calculate cpu usage percent
with open("/proc/stat", "r") as handle:
lines = [line.rstrip() for line in handle if line.startswith("cpu")]
types = ["user", "nice", "system", "idle", "iowait", "irq", "softirq", "steal", "guest", "guest_nice"]
usage = {}
for i, l in enumerate(lines):
if i < 1:
continue
raw = l.split(" ")
cpu = raw[0]
usage[cpu] = {}
for i, val in enumerate(types):
if not raw[i+1]:
continue
usage[cpu][val] = int(raw[i+1])
# Total cpu time since boot
# https://github.com/Leo-G/DevopsWiki/wiki/How-Linux-CPU-Usage-Time-and-Percentage-is-calculated
types = types[:8]
totalTimes = {}
for cpu, counters in usage.items():
totaltime = 0
for t in types:
totaltime += int(counters[t])
idle = counters["idle"] + counters["iowait"]
usage = totaltime - idle
totalTimes[cpu[3:].zfill(2)] = int( ( usage / totaltime ) * 100 )
freqs = [f for f in glob.glob("/sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq")]
data = {}
for f in freqs:
with open(f, "r") as handle:
f = f.split("/")
data[f[5][3:].zfill(2)] = int(int(handle.read().rstrip()) / 1000)
def ColorPrint(COLOR):
print(COLOR, k, "freq:", v, "usage:", totalTimes[k], RESET)
for k, v in sorted(data.items()):
if v > 4200:
ColorPrint(RED)
elif v > 4000:
ColorPrint(BLUE)
elif v > 3700:
ColorPrint(GREEN)
else:
print(k, "freq:", v, "usage:", totalTimes[k])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment