Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import re
- import time
- from statistics import mean
- from collections import namedtuple, defaultdict
- from pathlib import Path
- CPU_REGEX = re.compile("cpu(\d+)")
- CPU_STAT = Path("/proc/stat")
- STAT = namedtuple("stat", "cpu user nice system idle iowait irq softirq steal guest guest_nice")
- TOTAL_LAST = 0
- BUSY_LAST = 0
- def read_ticks():
- results = []
- stats = CPU_STAT.read_text()
- for line in stats.splitlines():
- match = CPU_REGEX.search(line)
- if match:
- cpu, *values = line.split()
- result = STAT(cpu, *map(int, values))
- busy_ticks = sum((result.user, result.nice, result.system, result.irq, result.softirq))
- total_ticks = sum((busy_ticks, result.idle, result.iowait))
- results.append((cpu, busy_ticks, total_ticks))
- return results
- def get_rel_load(interval=1):
- cpu, busy, total = zip(*read_ticks())
- last_busy = {cpu: busy for cpu, busy in zip(cpu, busy)}
- last_ticks = {cpu: total for cpu, total in zip(cpu, total)}
- result = []
- time.sleep(interval)
- for cpu, busy_ticks, total_ticks in read_ticks():
- result.append((
- cpu,
- (busy_ticks - last_busy[cpu]) / (total_ticks - last_ticks[cpu]) * 100,
- ))
- last_busy[cpu] = busy_ticks
- last_ticks[cpu] = total_ticks
- return result
- if __name__ == "__main__":
- #for results in get_rel_load():
- # print("\x1b[2J\x1b[H", end="")
- # for cpu, load in results:
- # print(f"[{cpu:<5}] {load:.1f} %")
- load = [load for cpu, load in get_rel_load()]
- print(mean(load))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement