Advertisement
DeaD_EyE

/proc/stat

Jun 8th, 2020
1,192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import re
  4. import time
  5. from statistics import mean
  6. from collections import namedtuple, defaultdict
  7. from pathlib import Path
  8.  
  9.  
  10.  
  11. CPU_REGEX = re.compile("cpu(\d+)")
  12. CPU_STAT = Path("/proc/stat")
  13. STAT = namedtuple("stat", "cpu user nice system idle iowait irq softirq steal guest guest_nice")
  14. TOTAL_LAST = 0
  15. BUSY_LAST = 0
  16.  
  17.  
  18. def read_ticks():
  19.     results = []
  20.     stats = CPU_STAT.read_text()
  21.     for line in stats.splitlines():
  22.         match = CPU_REGEX.search(line)
  23.         if match:
  24.             cpu, *values = line.split()
  25.             result = STAT(cpu, *map(int, values))
  26.             busy_ticks = sum((result.user, result.nice, result.system, result.irq, result.softirq))
  27.             total_ticks = sum((busy_ticks, result.idle, result.iowait))
  28.             results.append((cpu, busy_ticks, total_ticks))
  29.     return results
  30.  
  31.  
  32. def get_rel_load(interval=1):
  33.     cpu, busy, total = zip(*read_ticks())
  34.     last_busy = {cpu: busy for cpu, busy in zip(cpu, busy)}
  35.     last_ticks = {cpu: total for cpu, total in zip(cpu, total)}
  36.     result = []
  37.     time.sleep(interval)
  38.     for cpu, busy_ticks, total_ticks in read_ticks():
  39.         result.append((
  40.             cpu,
  41.             (busy_ticks - last_busy[cpu]) / (total_ticks - last_ticks[cpu]) * 100,
  42.         ))
  43.         last_busy[cpu] = busy_ticks
  44.         last_ticks[cpu] = total_ticks
  45.     return result
  46.  
  47.  
  48.  
  49. if __name__ == "__main__":
  50.     #for results in get_rel_load():
  51.     #    print("\x1b[2J\x1b[H", end="")
  52.     #    for cpu, load in results:
  53.     #        print(f"[{cpu:<5}] {load:.1f} %")
  54.     load = [load for cpu, load in get_rel_load()]
  55.     print(mean(load))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement