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

时间秒杀一切 提交于 2019-12-04 04:06:50

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

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