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

Using the following code, I can get the memory consumption of the issuing 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 the %MEM column when I execute the top command in the terminal for a specific process.

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

enter image description here

+6
source share
2 answers

use process.memory_percent()

This is consistent with the top. In the test script below, you can change the argument to a range function that defines the consume_memory array, which is used only to use memory for testing, and both the output to python and the top output will correspond:

 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

+8
source
 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)) 
0
source

Source: https://habr.com/ru/post/969901/


All Articles