Changeset 336

Show
Ignore:
Timestamp:
06/21/08 00:17:17 (4 years ago)
Author:
simon
Message:

Add memory recipe. Make 2.5/2.6/3.0 compatible.

Files:
1 modified

Legend:

Unmodified
Added
Removed
  • hodgestar/Talks/PythonObjects/util.py

    r333 r336  
    2525    answer, err = egrep.communicate() 
    2626 
    27     print "Which module does the keyword %s appear in?" % question 
     27    print ("Which module does the keyword " + question + " appear in?") 
    2828    for i in reversed(range(5)): 
    29         sys.stdout.write("%s ... " % i) 
     29        sys.stdout.write(str(i) + " ... ") 
    3030        sys.stdout.flush() 
    3131        time.sleep(1) 
    32     print "" 
    33     print "-- Answers --" 
    34     print answer 
     32    print ("") 
     33    print ("-- Answers --") 
     34    print (answer) 
    3535 
     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 
     46def _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 
     65def memory(since=0.0): 
     66    '''Return memory usage in bytes. 
     67    ''' 
     68    return _VmB('VmSize:') - since 
     69 
     70 
     71def resident(since=0.0): 
     72    '''Return resident memory usage in bytes. 
     73    ''' 
     74    return _VmB('VmRSS:') - since 
     75 
     76 
     77def stacksize(since=0.0): 
     78    '''Return stack size in bytes. 
     79    ''' 
     80    return _VmB('VmStk:') - since 
     81 
     82# END Recipe