13

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

B Faley
  • 17,120
  • 43
  • 133
  • 223
  • 1
    Providing your definition of "percentage of memory consumption" will make it more obvious what you need to do. – Jonathon Reinhart May 03 '15 at 13:22
  • Again, providing the definition of that value will lead you to your answer. What, in simple terms, does it mean? Percentage *of what*? – Jonathon Reinhart May 03 '15 at 13:29
  • 1
    See http://stackoverflow.com/questions/19538263/how-to-extract-just-the-percentage-from-psutil-phymem-usage-python. – Mihai8 May 03 '15 at 13:34
  • @JonathonReinhart Added an example – B Faley May 03 '15 at 13:39
  • @Paul No, that's not what I need. It "_Return the amount of total, used and free physical memory on the system in bytes plus the percentage usage._" I do not need the total value. I need that value for a specific process only. – B Faley May 03 '15 at 13:43
  • Wonder how accurate you need this to be? I made a loop to continuously `print psutil.phymem_usage().percent` but I get a different number in `top` for the running python process. – Paul May 03 '15 at 13:44
  • Ah, I see what's happening. That's not a duplicate then. – Paul May 03 '15 at 13:45

2 Answers2

20

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

Paul
  • 26,170
  • 12
  • 85
  • 119
2
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))