Skip to content

Instantly share code, notes, and snippets.

@robertknight
Last active July 20, 2021 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertknight/7151786998494b8619b56e18edb5198e to your computer and use it in GitHub Desktop.
Save robertknight/7151786998494b8619b56e18edb5198e to your computer and use it in GitHub Desktop.
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":
continue
amount, unit = [field.strip() for field in val.split(" ")]
amount = int(amount)
if unit == "kB":
scale = 1024
else:
# 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"{pid},{cmdline},{private_mbs}")
print(f"System total: {system_total}")
@robertknight
Copy link
Author

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