8

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

ʞɔıu
  • 47,148
  • 35
  • 106
  • 149

5 Answers5

11

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
  • 124,830
  • 17
  • 198
  • 235
4

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.

Community
  • 1
  • 1
Alex
  • 6,843
  • 10
  • 52
  • 71
2

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
  • 1,203
  • 2
  • 10
  • 19
1

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
  • 27,541
  • 5
  • 35
  • 31
0

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,217
  • 10
  • 16