Skip to content

Instantly share code, notes, and snippets.

@lilydjwg
Last active July 20, 2019 07:47
Show Gist options
  • Save lilydjwg/60c854d82b612b33c6785235c44019a1 to your computer and use it in GitHub Desktop.
Save lilydjwg/60c854d82b612b33c6785235c44019a1 to your computer and use it in GitHub Desktop.
show-mem-usage: parse /proc/{pid}/maps and show how much memory is used by each file/type
#!/usr/bin/python3
'''parse /proc/{pid}/smaps and show how much RSS memory is used by each file/type'''
import sys
from collections import defaultdict
def filesize(size: int) -> str:
units = 'KMGTPEZY'
left = abs(size)
unit = -1
n = len(units)
while left > 1100 and unit < n:
left = left / 1024
unit += 1
if unit == -1:
return '%dB' % size
else:
if size < 0:
left = -left
return '%.1f%siB' % (left, units[unit])
def main():
data = defaultdict(int)
maxlen = 0
for line in sys.stdin:
first, second, *others, last = line.split(None, 5)
if len(others) == 3:
name = last.rstrip()
elif len(others) == 2:
name = '[anon]'
else:
if first == 'Rss:':
data[name] += int(second)
maxlen = max(maxlen, len(name))
for name, used in sorted(
data.items(), key=lambda x: x[1]):
size = filesize(used * 1024)
size = size[:-3] + ' ' + size[-3:]
print(f'{name:{maxlen}} {size:>10}')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment