Memory usage of a single process with psutil in python (in byte)

pafpaf picture pafpaf · Nov 20, 2014 · Viewed 8.2k times · Source

How to get the amount of memory which has been used by a single process in windows platform with psutil library? (I dont want to have the percentage , I want to know the amount in bytes)

We can use:

psutil.virtual_memory().used

To find the memory usage of the whole OS in bytes, but how about each single process?

Thanks,

Answer

Eryk Sun picture Eryk Sun · Nov 20, 2014

Call memory_info_ex:

>>> import psutil
>>> p = psutil.Process()
>>> p.name()
'python.exe'

>>> _ = p.memory_info_ex()
>>> _.wset, _.pagefile
(11665408, 8499200)

The working set includes pages that are shared or shareable by other processes, so in the above example it's actually larger than the paging file commit charge.

There's also a simpler memory_info method. This returns rss and vms, which correspond to wset and pagefile.

>>> p.memory_info()
pmem(rss=11767808, vms=8589312)

For another example, let's map some shared memory.

>>> import mmap
>>> m = mmap.mmap(-1, 10000000)
>>> p.memory_info()            
pmem(rss=11792384, vms=8609792)

The mapped pages get demand-zero faulted into the working set.

>>> for i in range(0, len(m), 4096): m[i] = 0xaa
...
>>> p.memory_info()                             
pmem(rss=21807104, vms=8581120)

A private copy incurs a paging file commit charge:

>>> s = m[:]
>>> p.memory_info()
pmem(rss=31830016, vms=18604032)