1import os 2 3_proc_status = '/proc/%d/status' % os.getpid() 4#_scale = {'kB': 1024.0, 'mB': 1024.0*1024.0, 5# 'KB': 1024.0, 'MB': 1024.0*1024.0} 6 7_scale = {'kB': 1, 'mB': 1024, 'gB': 1024 * 1024, 8 'KB': 1, 'MB': 1024, 'GB': 1024 * 1024} 9 10 11def _VmB(VmKey): 12 '''Private. 13 ''' 14 global _proc_status, _scale 15 # get pseudo file /proc/<pid>/status 16 try: 17 t = open(_proc_status) 18 v = t.read() 19 t.close() 20 except: 21 return float('nan') # non-Linux? 22 # get VmKey line e.g. 'VmRSS: 9999 kB\n ...' 23 i = v.index(VmKey) 24 v = v[i:].split(None, 3) # whitespace 25 if len(v) < 3: 26 return float('nan') # invalid format? 27 # convert Vm value to bytes 28 # return float(v[1]) * _scale[v[2]] 29 return int(v[1]) * _scale[v[2]] 30 31 32def memory(since=0): 33 '''Return memory usage in kilobytes. 34 ''' 35 return _VmB('VmSize:') - since 36 37 38def resident(since=0): 39 '''Return resident memory usage in kilobytes. 40 ''' 41 return _VmB('VmRSS:') - since 42 43 44def memorypeak(since=0): 45 '''Return memory usage peak in kilobytes. 46 ''' 47 try: 48 return _VmB('VmPeak:') - since 49 except: 50 return float('nan') # old Linux? 51 52 53def residentpeak(since=0): 54 '''Return resident memory usage peak in kilobytes. 55 ''' 56 try: 57 return _VmB('VmHWM:') - since 58 except: 59 return float('nan') # old Linux? 60 61 62def stacksize(since=0): 63 '''Return stack size in kilobytes. 64 ''' 65 return _VmB('VmStk:') - since 66