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.
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))
来源:https://stackoverflow.com/questions/30014295/how-to-get-the-percentage-of-memory-usage-of-a-process