Skip to content

Instantly share code, notes, and snippets.

@hualet
Created July 9, 2018 07:49
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 hualet/e3b008319984fb2cba326e39a24d95e1 to your computer and use it in GitHub Desktop.
Save hualet/e3b008319984fb2cba326e39a24d95e1 to your computer and use it in GitHub Desktop.
Calculate /proc/*/maps statistics
#!/usr/bin/env python3
import sys
import os.path
usage = \
'''
Usage: mapstat PID
'''
def print_usage():
print(usage)
sys.exit(-1)
def parse_line(line):
tokens = list(filter(lambda x: x, line.split(' ')))
if len(tokens) == 6:
mem_range = tokens[0]
mem_start, mem_end = map(lambda x: int('0x'+x, 16), mem_range.split('-'))
mem_size = mem_end - mem_start
map_file = tokens[-1].strip()
return (mem_size, map_file) if (mem_size and map_file) else None
return None
def human_readable(num):
if num < 1024:
return str(num) + 'B'
elif num < 1024 ** 2:
return str(int(num / 1024)) + 'KB'
elif num < 1024 ** 3:
return str(int(num / 1024**2)) + 'MB'
def main():
if len(sys.argv) != 2:
print_usage()
try:
pid = int(sys.argv[1])
except:
print_usage()
map_file = '/proc/%d/maps' % pid
if not os.path.exists(map_file):
print_usage()
cache = {}
with open(map_file) as maps:
for line in maps:
result = parse_line(line)
if result:
size, map_file = result
cache[map_file] = cache.get(map_file, 0) + size
sorted_keys = sorted(cache.keys(), key=lambda x: cache[x], reverse=True)
for map_file in sorted_keys:
size = human_readable(cache[map_file])
print(size, '\t', map_file)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment