Created
July 6, 2018 09:53
-
-
Save smutch/38d0fadfb9154e6626ebdf9c3e51cea4 to your computer and use it in GitHub Desktop.
Monitor the total memory of a process and its children
This file contains hidden or 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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
from subprocess import run, PIPE | |
import os | |
from time import sleep | |
import click | |
@click.command() | |
@click.argument('pid', type=click.INT) | |
@click.option('--every', type=click.INT, default=5) | |
def monitor(pid, every=5): | |
print(f"Monitoring PID {pid}...") | |
username = os.environ['USER'] | |
ret = run(f"ps -o pid,ppid,pgid,comm,rss -u {username} " | |
f"| grep {pid}", shell=True, stdout=PIPE) | |
max_mem = 0 | |
try: | |
while True: | |
mem = sum((int(line.split()[-1]) for line in | |
ret.stdout.decode('utf-8').splitlines())) / 1024 / 1024 | |
if mem > max_mem: | |
max_mem = mem | |
print(f"Current usage = {mem:.2f} GB") | |
print(f"Max usage = {max_mem:.2f} GB") | |
sleep(every) | |
print("\033[F\033[K\033[F\033[K", end='') | |
except KeyboardInterrupt: | |
print(f"\nCurrent usage = {mem:.2f} GB") | |
print(f"Max usage = {max_mem:.2f} GB") | |
if __name__ == "__main__": | |
monitor() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment