Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the percentage of memory usage of a process?

Using the following code, I can get the memory consumption of a give process in MiB:

def memory_usage_psutil():
    # return the memory usage in MB
    import psutil
    process = psutil.Process(os.getpid())
    mem = process.get_memory_info()[0] / float(2 ** 20)
    return mem

How can I change this to return the percentage of memory consumption?

Update: I need to get the current value of %MEM column when executing the top command in terminal for a specific process.

Example: I need this function to return 14.2 for the process id of VirtualBox process.

enter image description here

like image 444
B Faley Avatar asked May 03 '15 13:05

B Faley


2 Answers

use process.memory_percent()

This agrees with top. In the test script below, you can change the argument to the range function defining the consume_memory array, which is only there to use up memory for testing, and both python output and top output will match:

import os
import psutil

def memory_usage_psutil():
    # return the memory usage in percentage like top
    process = psutil.Process(os.getpid())
    mem = process.memory_percent()
    return mem

consume_memory = range(20*1000*1000)

while True:
    print memory_usage_psutil()

pythonVstop

like image 196
Paul Avatar answered Oct 27 '22 13:10

Paul


import os
import sys
import psutil


for id in psutil.pids():
    p = psutil.Process(id)
    if ( p.name() == 'firefox' ):
        print("id of firefox process : " + str(id))
        mem = p.memory_percent()
        print ("Memory Perentage for Firefox process is " + str(mem))
like image 25
Ashwini Kumar Avatar answered Oct 27 '22 13:10

Ashwini Kumar