Skip to content

Instantly share code, notes, and snippets.

@RasmusFonseca
Last active July 2, 2018 20:16
Show Gist options
  • Save RasmusFonseca/31d163c6c0cd0f3cfea260fbc7ae38ca to your computer and use it in GitHub Desktop.
Save RasmusFonseca/31d163c6c0cd0f3cfea260fbc7ae38ca to your computer and use it in GitHub Desktop.
Monitor CPU-time and max memory usage using ps
"""
Monitors a process using the `ps` command and records total CPU-time and maximum memory usage.
Example usage:
./runMyCommand &
sysusg.py runMyCommand
"""
import subprocess
import sys
import time
def ps(grep_for):
proc = subprocess.Popen(["ps", "-A", "-o", "pid,ppid,etime,rss,args"], stdout=subprocess.PIPE)
(out, err) = proc.communicate()
second_multipliers = [1, 60, 3600, 86400]
max_time = 0
total_rss = 0
found_command = False
for line in str(out, 'utf-8').split("\n"):
if command_contains in line and sys.argv[0] not in line:
found_command = True
tokens = line.split()
time_tokens = list(map(float, tokens[2].split(":")))
time_tokens_secs = [t * second_multipliers[len(time_tokens) - 1 - i] for i,t in enumerate(time_tokens)]
time_s = sum(time_tokens_secs)
max_time = max(max_time, time_s)
total_rss += int(tokens[3])
if found_command:
return max_time, total_rss
else:
return None
command_contains = sys.argv[1]
sample_delay = 0.2 # Unit is seconds
print("Analyzing all processes whose command contains '" + command_contains + "'")
print("Waiting for process(es) to start")
while ps(command_contains) is None:
time.sleep(sample_delay)
print("Sampling memory and running time every", sample_delay, "seconds until processes finish")
max_rss = 0
max_time = 0
try:
while True:
max_time, rss = ps(command_contains)
max_rss = max(max_rss, rss)
time.sleep(sample_delay)
sys.stdout.write(".")
sys.stdout.flush()
except TypeError:
pass
print("")
print("Time:", max_time, "seconds")
print("Memory:", max_rss / 1024.0, "MB")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment