Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting total/free RAM from within Python

From within a Python application, how can I get the total amount of RAM of the system and how much of it is currently free, in a cross-platform way?

Ideally, the amount of free RAM should consider only physical memory that can actually be allocated to the Python process.

like image 377
Algorias Avatar asked Jul 30 '09 03:07

Algorias


People also ask

How do I free up RAM in Python?

del and gc. collect() are the two different methods to delete the memory in python. The clear memory method is helpful to prevent the overflow of memory. We can delete that memory whenever we have an unused variable, list, or array using these two methods.

How do I see RAM usage in Python?

The function psutil. virutal_memory() returns a named tuple about system memory usage. The third field in the tuple represents the percentage use of the memory(RAM). It is calculated by (total – available)/total * 100 .

How do I get CPU usage in Python?

Use the os Module to Retrieve Current CPU Usage in Python We can use the cpu_count() function from this module to retrieve the CPU usage. The psutil. getloadavg() function provides the load information about the CPU in the form of a tuple. The result obtained from this function gets updated after every five minutes.


2 Answers

Have you tried SIGAR - System Information Gatherer And Reporter? After install

import os, sigar

sg = sigar.open()
mem = sg.mem()
sg.close() 
print mem.total() / 1024, mem.free() / 1024

Hope this helps

like image 163
sunqiang Avatar answered Oct 26 '22 00:10

sunqiang


psutil would be another good choice. It also needs a library installed however.

>>> import psutil
>>> psutil.virtual_memory()
vmem(total=8374149120L, available=2081050624L, percent=75.1,
     used=8074080256L, free=300068864L, active=3294920704,
     inactive=1361616896, buffers=529895424L, cached=1251086336)
like image 44
Gringo Suave Avatar answered Oct 25 '22 23:10

Gringo Suave