Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get total physical memory in Python

How can I get the total physical memory within Python in a distribution agnostic fashion? I don't need used memory, just the total physical memory.

like image 333
Justin Avatar asked Feb 28 '14 18:02

Justin


People also ask

How do I get the total RAM in Python?

You could read /proc/meminfo . /proc/meminfo should be available on pretty much all linux installs. You don't need /proc/meminfo because sysconf has the answer.

How do I check my total memory?

Press Ctrl + Shift + Esc to launch Task Manager. Or, right-click the Taskbar and select Task Manager. Select the Performance tab and click Memory in the left panel. The Memory window lets you see your current RAM usage, check RAM speed, and view other memory hardware specifications.

How do I check memory in Python?

You can use it by putting the @profile decorator around any function or method and running python -m memory_profiler myscript. You'll see line-by-line memory usage once your script exits.

How do I get CPU info in Python?

CPU Information psutil's cpu_count() function returns number of cores, whereas cpu_freq() function returns CPU frequency as a namedtuple including current, min, and max frequency expressed in Mhz, you can set percpu=True to get per CPU frequency.


2 Answers

your best bet for a cross-platform solution is to use the psutil package (available on PyPI).

import psutil
    
psutil.virtual_memory().total  # total physical memory in Bytes

Documentation for virtual_memory is here.

like image 77
Corey Goldberg Avatar answered Oct 19 '22 17:10

Corey Goldberg


Using os.sysconf on Linux:

import os
mem_bytes = os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES')  # e.g. 4015976448
mem_gib = mem_bytes/(1024.**3)  # e.g. 3.74

Note:

  • SC_PAGE_SIZE is often 4096.
  • SC_PAGESIZE and SC_PAGE_SIZE are equal.
  • For more info, see man sysconf.
  • For MacOS, as per user reports, this works with Python 3.7 but not with Python 3.8.

Using /proc/meminfo on Linux:

meminfo = dict((i.split()[0].rstrip(':'),int(i.split()[1])) for i in open('/proc/meminfo').readlines())
mem_kib = meminfo['MemTotal']  # e.g. 3921852
like image 64
Asclepius Avatar answered Oct 19 '22 17:10

Asclepius