Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Estimate private memory usage of a list of processes
import os
import sys
def process_private_memory(pid):
smaps_path = f"/proc/{pid}/smaps"
total = 0
for line in open(smaps_path, 'r'):
field, val = [val.strip() for val in line.split(':')]
if field != "Private_Dirty":
amount, unit = [field.strip() for field in val.split(" ")]
amount = int(amount)
if unit == "kB":
scale = 1024
# TODO - Handle other units if encountered.
raise Exception(f"Unknown unit {unit}")
total += amount * scale
return total
def process_cmdline(pid):
cmd = open(f"/proc/{pid}/comm", "r").read().strip()
args = open(f"/proc/{pid}/cmdline", "r").read().strip().split("\x00")
return f"{' '.join(args)}".strip()
pids = [pid for pid in sys.argv[1:] if os.path.exists(f"/proc/{pid}/comm")]
stats = [(pid, process_cmdline(pid), process_private_memory(pid) / (1024*1024)) for pid in pids]
stats = sorted(stats, key=lambda stats: stats[2])
system_total = 0
for pid, cmdline, private_mbs in stats:
system_total += private_mbs
print(f"System total: {system_total}")
Copy link

robertknight commented Jul 20, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment