How to get the percentage of memory usage of a process?
Asked Answered
Q

2

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

Qnp answered 3/5, 2015 at 13:20 Comment(7)
Providing your definition of "percentage of memory consumption" will make it more obvious what you need to do.Execratory
Again, providing the definition of that value will lead you to your answer. What, in simple terms, does it mean? Percentage of what?Execratory
See #19538763.Hyonhyoscine
@JonathonReinhart Added an exampleQnp
@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.Qnp
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.Lesialesion
Ah, I see what's happening. That's not a duplicate then.Lesialesion
L
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

Lesialesion answered 3/5, 2015 at 13:53 Comment(0)
D
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))
Davon answered 5/5, 2015 at 6:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.