Mercurial > pylearn
comparison common/memory.py @ 355:430c9e92cd23
Added common directory
author | Joseph Turian <turian@iro.umontreal.ca> |
---|---|
date | Thu, 19 Jun 2008 16:12:29 -0400 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
354:d580b3a369a4 | 355:430c9e92cd23 |
---|---|
1 """ | |
2 Determine memory usage of a program:: | |
3 m0 = memory() | |
4 ... | |
5 m1 = memory(m0) | |
6 @note: From U{http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286222/index_txt} | |
7 @warning: Not portable. | |
8 """ | |
9 | |
10 import os | |
11 | |
12 _proc_status = '/proc/%d/status' % os.getpid() | |
13 | |
14 _scale = {'kB': 1024.0, 'mB': 1024.0*1024.0, | |
15 'KB': 1024.0, 'MB': 1024.0*1024.0} | |
16 | |
17 def _VmB(VmKey): | |
18 '''Private. | |
19 ''' | |
20 global _proc_status, _scale | |
21 # get pseudo file /proc/<pid>/status | |
22 try: | |
23 t = open(_proc_status) | |
24 v = t.read() | |
25 t.close() | |
26 except: | |
27 return 0.0 # non-Linux? | |
28 # get VmKey line e.g. 'VmRSS: 9999 kB\n ...' | |
29 i = v.index(VmKey) | |
30 v = v[i:].split(None, 3) # whitespace | |
31 if len(v) < 3: | |
32 return 0.0 # invalid format? | |
33 # convert Vm value to bytes | |
34 return float(v[1]) * _scale[v[2]] | |
35 | |
36 | |
37 def memory(since=0.0): | |
38 '''Return memory usage in bytes. | |
39 ''' | |
40 return _VmB('VmSize:') - since | |
41 | |
42 | |
43 def resident(since=0.0): | |
44 '''Return resident memory usage in bytes. | |
45 ''' | |
46 return _VmB('VmRSS:') - since | |
47 | |
48 | |
49 def stacksize(since=0.0): | |
50 '''Return stack size in bytes. | |
51 ''' | |
52 return _VmB('VmStk:') - since |