Changeset 6578


Ignore:
Timestamp:
Mar 23, 2009, 12:34:59 PM (15 years ago)
Author:
rwilson
Message:

Added memory usage routine and test cases.

Location:
anuga_core/source/anuga/utilities
Files:
1 added
1 edited

Legend:

Unmodified
Added
Removed
  • anuga_core/source/anuga/utilities/log.py

    r6527 r6578  
    2020
    2121import sys
    22 import os.path
     22import os
     23#import os.path
     24import sys
    2325import traceback
    2426import logging
     
    130132    log(logging.CRITICAL, msg)
    131133
     134def resource_usage(level=logging.CRITICAL):
     135    '''Log resource usage at given log level.'''
     136
     137    if sys.platform != 'win32':
     138        _proc_status = '/proc/%d/status' % os.getpid()
     139        _scale = {'KB': 1024.0, 'MB': 1024.0*1024.0, 'GB': 1024.0*1024.0*1024.0,
     140                  'kB': 1024.0, 'mB': 1024.0*1024.0, 'gB': 1024.0*1024.0*1024.0}
     141
     142        def _VmB(VmKey):
     143            '''Get number of virtual bytes used.'''
     144
     145            # get pseudo file /proc/<pid>/status
     146            try:
     147                t = open(_proc_status)
     148                v = t.read()
     149                t.close()
     150            except IOError:
     151                return 0.0
     152
     153            # get VmKey line, eg: 'VmRSS: 999 kB\n ...
     154            i = v.index(VmKey)
     155            v = v[i:].split(None, 3)
     156            if len(v) < 3:
     157                return 0.0
     158
     159            # convert Vm value to bytes
     160            return float(v[1]) * _scale[v[2]]
     161
     162        def memory(since=0.0):
     163            '''Get virtual memory usage in bytes.'''
     164
     165            return _VmB('VmSize:') - since
     166
     167        def resident(since=0.0):
     168            '''Get resident memory usage in bytes.'''
     169
     170            return _VmB('VmRSS:') - since
     171
     172        def stacksize(since=0.0):
     173            '''Get stack size in bytes.'''
     174
     175            return _VmB('VmStk:') - since
     176
     177        msg = ('Resource usage: memory=%.1f resident=%.1f stacksize=%.1f'
     178               % (memory()/_scale['GB'], resident()/_scale['GB'],
     179                  stacksize()/_scale['GB']))
     180        log(level, msg)
     181    else:
     182        pass
Note: See TracChangeset for help on using the changeset viewer.