Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine free RAM in Python

I would like my python script to use all the free RAM available but no more (for efficiency reasons). I can control this by reading in only a limited amount of data but I need to know how much RAM is free at run-time to get this right. It will be run on a variety of Linux systems. Is it possible to determine the free RAM at run-time?

like image 346
marshall Avatar asked Jul 18 '13 08:07

marshall


People also ask

How do I know my RAM size for free?

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 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 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.

Does Python free memory after function call?

If you don't manually free() the memory allocated by malloc() , it will never get freed. Python, in contrast, tracks objects and frees their memory automatically when they're no longer used.


2 Answers

On Linux systems I use this from time to time:

def memory():
    """
    Get node total memory and memory usage
    """
    with open('/proc/meminfo', 'r') as mem:
        ret = {}
        tmp = 0
        for i in mem:
            sline = i.split()
            if str(sline[0]) == 'MemTotal:':
                ret['total'] = int(sline[1])
            elif str(sline[0]) in ('MemFree:', 'Buffers:', 'Cached:'):
                tmp += int(sline[1])
        ret['free'] = tmp
        ret['used'] = int(ret['total']) - int(ret['free'])
    return ret

You can run this when your script starts up. RAM is usually used and freed pretty frequently on a busy system, so you should take that into account before deciding how much RAM to use. Also, most linux systems have a swappiness value of 60. When using up memory, pages that are least frequently used will be swapped out. You may find yourself using SWAP instead of RAM.

Hope this helps.

like image 117
Gabriel Samfira Avatar answered Oct 11 '22 03:10

Gabriel Samfira


Another option is the Python package psutil:

stats = psutil.virtual_memory()  # returns a named tuple
available = getattr(stats, 'available')
print(available)

According to the documentation, the available field "is calculated by summing different memory values depending on the platform and it is supposed to be used to monitor actual memory usage in a cross platform fashion."

Note the return value will be in bytes

like image 38
Addison Klinke Avatar answered Oct 11 '22 04:10

Addison Klinke