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

跟風遠走 提交于 2019-12-05 22:10:31

问题


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.


回答1:


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()




回答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))


来源:https://stackoverflow.com/questions/30014295/how-to-get-the-percentage-of-memory-usage-of-a-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!