Last active
August 29, 2015 14:23
-
-
Save jeffp123/10d58e88ccd430a49411 to your computer and use it in GitHub Desktop.
Python 2.3 Compatible Memory Profiler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MemoryProfiler: | |
def mem(self, size="rss"): | |
"""Generalization; memory sizes: rss, rsz, vsz.""" | |
return os.popen('ps -p %d -o %s | tail -1' % (os.getpid(), size)).read() | |
def rss(self): | |
"""Return ps -o rss (resident) memory in kB.""" | |
return self.convert_kilobytes(self.mem("rss")) | |
def rsz(self): | |
"""Return ps -o rsz (resident + text) memory in kB.""" | |
return self.convert_kilobytes(self.mem("rsz")) | |
def vsz(self): | |
"""Return ps -o vsz (virtual) memory in kB.""" | |
return self.convert_kilobytes(self.mem("vsz")) | |
def convert_kilobytes(self, kilobytes): | |
kilobytes = float(kilobytes) | |
return self.convert_bytes(kilobytes * 1024) | |
def convert_bytes(self, bytes): | |
bytes = float(bytes) | |
if bytes >= 1099511627776: | |
terabytes = bytes / 1099511627776 | |
size = '%.2fT' % terabytes | |
elif bytes >= 1073741824: | |
gigabytes = bytes / 1073741824 | |
size = '%.2fG' % gigabytes | |
elif bytes >= 1048576: | |
megabytes = bytes / 1048576 | |
size = '%.2fM' % megabytes | |
elif bytes >= 1024: | |
kilobytes = bytes / 1024 | |
size = '%.2fK' % kilobytes | |
else: | |
size = '%.2fb' % bytes | |
return size | |
def print_usage(label=""): | |
memory_profiler = MemoryProfiler() | |
output = "" | |
if label: | |
output += label + ": " | |
output += "RSS: %s; RSZ: %s; VSZ: %s" %\ | |
(memory_profiler.rss(), memory_profiler.rsz(), memory_profiler.vsz()) | |
print output | |
print_usage = staticmethod(print_usage) |
Note, this class derived from answers found on StackOverflow
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use, call this anywhere: