Skip to content

Instantly share code, notes, and snippets.

@candale
Last active May 31, 2017 09:24
Show Gist options
  • Save candale/1b522a07345c0bf9577332cd1a59cdb6 to your computer and use it in GitHub Desktop.
Save candale/1b522a07345c0bf9577332cd1a59cdb6 to your computer and use it in GitHub Desktop.
Python heap usage
# From stackoverflow answer https://stackoverflow.com/a/938800
import os
_proc_status = '/proc/%d/status' % os.getpid()
_scale = {'kB': 1024.0, 'mB': 1024.0*1024.0,
'KB': 1024.0, 'MB': 1024.0*1024.0}
def _VmB(VmKey):
'''Private.
'''
global _proc_status, _scale
# get pseudo file /proc/<pid>/status
try:
t = open(_proc_status)
v = t.read()
t.close()
except:
return 0.0 # non-Linux?
# get VmKey line e.g. 'VmRSS: 9999 kB\n ...'
i = v.index(VmKey)
v = v[i:].split(None, 3) # whitespace
if len(v) < 3:
return 0.0 # invalid format?
# convert Vm value to bytes
return float(v[1]) * _scale[v[2]]
def memory(since=0.0):
'''Return memory usage in bytes.
'''
return _VmB('VmSize:') - since
def resident(since=0.0):
'''Return resident memory usage in bytes.
'''
return _VmB('VmRSS:') - since
# Oneliner, for pudb input; no exception handling, linux only
# Leaves behind a variable called `heap_size` that holds the heap size in bytes
import os; _proc_status = '/proc/%d/status' % os.getpid(); _scale = {'kB': 1024.0, 'mB': 1024.0*1024.0, 'KB': 1024.0, 'MB': 1024.0*1024.0}; t = open(_proc_status); v = t.read(); t.close() ; i = v.index('VmSize:'); v = v[i:].split(None, 3); heap_size = float(v[1]) * _scale[v[2]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment