Skip to content

Instantly share code, notes, and snippets.

@jeffp123
Last active August 29, 2015 14:23
Show Gist options
  • Save jeffp123/10d58e88ccd430a49411 to your computer and use it in GitHub Desktop.
Save jeffp123/10d58e88ccd430a49411 to your computer and use it in GitHub Desktop.
Python 2.3 Compatible Memory Profiler
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)
@jeffp123
Copy link
Author

To use, call this anywhere:

MemoryProfiler.print_usage("label")

@jeffp123
Copy link
Author

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