Last active
October 25, 2022 06:17
-
-
Save luuil/ff6ba1fe6587f64bb34fdb98e9200ca6 to your computer and use it in GitHub Desktop.
monitor system status, such as usage of cpu, memory etc.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import time | |
import subprocess | |
import shlex | |
import numpy as np | |
def run_process(tmpl, *args, **kwargs): | |
_args = args | |
cmd = tmpl.format(**kwargs) | |
print(cmd) | |
p = subprocess.Popen(shlex.split(cmd)) | |
return p | |
if __name__ == "__main__": | |
cmd_tmpl_exe = 'cartoon.exe' | |
cmd_tmpl_mnt = 'python monitor.py {pid}' | |
p1 = run_process(cmd_tmpl_exe) | |
p2 = run_process(cmd_tmpl_mnt, pid=p1.pid) | |
p1.wait() | |
p2.wait() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import time | |
import psutil | |
from psutil._common import bytes2human | |
import numpy as np | |
def cpu_mem(pid): | |
# get process | |
p = psutil.Process(pid) | |
cpu_percents = list() | |
mem_percents = list() | |
mem_values = list() | |
interval = 1 # polling seconds | |
while True: | |
if not psutil.pid_exists(pid): | |
print(f"{'*' * 10} process={pid} is stoped, monitor will stop too.") | |
break | |
cpu_percent = p.cpu_percent() / psutil.cpu_count() | |
cpu_percents.append(cpu_percent) | |
mem_percent = p.memory_percent() | |
mem_percents.append(mem_percent) | |
mem_value = p.memory_info().rss | |
mem_values.append(mem_value) | |
line = f"{'*' * 10} pid={p.pid} name={p.name()} cpu={cpu_percent:.2f}%\tmem={mem_percent:.2f}%({bytes2human(mem_value)})" | |
print(line) | |
time.sleep(interval) | |
cpu_percents = cpu_percents[1:] | |
mem_percents = mem_percents[1:] | |
mem_values = mem_values[1:] | |
print(mem_values) | |
return np.mean(cpu_percents), np.mean(mem_percents), np.mean(mem_values) | |
if __name__ == "__main__": | |
pid = int(sys.argv[1]) | |
print(f"{'*' * 10} monitoring pid={pid}") | |
cpu, mem, mem_v = cpu_mem(pid) | |
print(f"cpu_avg={cpu:.2f}%\tmem_avg={mem:.2f}%({bytes2human(mem_v)})") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment