Ben Chuanlong Du's Blog

It is never too late to learn.

Get Total Physical Memory in Python

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Using os.sysconf

Notice that this ways only works on Linux but not on macOS or Windows.

Get physical memory in bytes.

In [1]:
import os
In [5]:
os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES")
Out[5]:
67327844352

Parse the File /proc/meminfo

In [7]:
!head /proc/meminfo
MemTotal:       65749848 kB
MemFree:          632084 kB
MemAvailable:   52502788 kB
Buffers:         1528080 kB
Cached:         47313580 kB
SwapCached:           60 kB
Active:         18386936 kB
Inactive:       40492096 kB
Active(anon):       5928 kB
Inactive(anon): 10750316 kB

Get physical memory in KB.

In [9]:
with Path("/proc/meminfo").open() as fin:
    line = fin.readline()
    if line.startswith("MemTotal:"):
        print(int(line[9:-3]))
65749848
In [12]:
65749848 * 1024
Out[12]:
67327844352

Using psutil

In [10]:
import psutil
In [11]:
psutil.virtual_memory()
Out[11]:
svmem(total=67327844352, available=53696008192, percent=20.2, used=12146085888, free=561696768, active=18897117184, inactive=41479438336, buffers=1565102080, cached=53054959616, shared=806260736, slab=5218934784)
In [13]:
psutil.virtual_memory().total
Out[13]:
67327844352

Of course, psutil is much more powerful. It is capable of getting process-level resource consumption. For more discussion, please refer to Hands on the psutil Module in Python .

In [ ]:
 

Comments