Last active
July 20, 2021 11:45
-
-
Save robertknight/7151786998494b8619b56e18edb5198e to your computer and use it in GitHub Desktop.
Estimate private memory usage of a list of processes
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
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}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Derived from https://stackoverflow.com/a/16597463/434243