| | 36 | |
| | 37 | # From: |
| | 38 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286222 |
| | 39 | # |
| | 40 | |
| | 41 | _proc_status = '/proc/' + str(os.getpid()) + '/status' |
| | 42 | |
| | 43 | _scale = {'kB': 1024.0, 'mB': 1024.0*1024.0, |
| | 44 | 'KB': 1024.0, 'MB': 1024.0*1024.0} |
| | 45 | |
| | 46 | def _VmB(VmKey): |
| | 47 | '''Private. |
| | 48 | ''' |
| | 49 | global _proc_status, _scale |
| | 50 | # get pseudo file /proc/<pid>/status |
| | 51 | try: |
| | 52 | t = open(_proc_status) |
| | 53 | v = t.read() |
| | 54 | t.close() |
| | 55 | except: |
| | 56 | return 0.0 # non-Linux? |
| | 57 | # get VmKey line e.g. 'VmRSS: 9999 kB\n ...' |
| | 58 | i = v.index(VmKey) |
| | 59 | v = v[i:].split(None, 3) # whitespace |
| | 60 | if len(v) < 3: |
| | 61 | return 0.0 # invalid format? |
| | 62 | # convert Vm value to bytes |
| | 63 | return float(v[1]) * _scale[v[2]] |
| | 64 | |
| | 65 | def memory(since=0.0): |
| | 66 | '''Return memory usage in bytes. |
| | 67 | ''' |
| | 68 | return _VmB('VmSize:') - since |
| | 69 | |
| | 70 | |
| | 71 | def resident(since=0.0): |
| | 72 | '''Return resident memory usage in bytes. |
| | 73 | ''' |
| | 74 | return _VmB('VmRSS:') - since |
| | 75 | |
| | 76 | |
| | 77 | def stacksize(since=0.0): |
| | 78 | '''Return stack size in bytes. |
| | 79 | ''' |
| | 80 | return _VmB('VmStk:') - since |
| | 81 | |
| | 82 | # END Recipe |