views:

427

answers:

5

How can a python script know the amount of system memory it's currently using? (assuming a unix-based OS)

+1  A: 

Similar question:

Python memory profiler

Looks like there are memory profilers for python.

PySizer seems popular. Heapy is another.

Google: "python memory profiler" for more.

windfinder
+1 - very similar. I think this question could be closed as a duplicate.
ire_and_curses
+6  A: 

If you want to know the total memory that the interpreter uses, on Linux, read /proc/self/statm.

If you want to find out how much memory your objects use, use Pympler.

Martin v. Löwis
A: 

I don't think there's a simple way to do this. As a practical matter, on a Unix OS I'd probably do something with os.getpid() and calling ps or reading entries in /proc.

Python 2.6 adds sys.getsizeof(), which you could use in concert with gc.get_objects() to walk the size of the working set of objects:

>>> print sum([sys.getsizeof(o) for o in gc.get_objects()])
561616

I don't think that'd be a good idea in practice.

Nelson
A: 

I haven't used it, but you might take a look at heapy (http://guppy-pe.sourceforge.net/#Heapy), which looks to be a memory profiler for python programs.

Jim
+1  A: 

I've used once snippet I found on ActiveState and it seemed to work well. Actually it's using same method Martin v. Löwis suggested.

Chris Ciesielski