[英]How to get the percentage of memory usage of a process?
Using the following code, I can get the memory consumption of a give process in MiB: 使用以下代码,我可以在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. 更新 :在终端中为特定进程执行
top
命令时,我需要获取%MEM
列的当前值。
Example : I need this function to return 14.2 for the process id of VirtualBox process. 示例 :我需要此函数返回14.2以获取VirtualBox进程的进程ID。
use process.memory_percent()
使用
process.memory_percent()
This agrees with top. 这与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: 在下面的测试脚本中,您可以将参数更改为定义
consume_memory
数组的范围函数,该数组仅用于使用内存进行测试,并且python输出和顶部输出都将匹配:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.