如何获取进程的内存使用率百分比? [英] How to get the percentage of memory usage of a process?
问题描述
使用以下代码,我可以在MiB中获取给定进程的内存消耗:
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?
更新:在终端中为特定进程执行top
命令时,我需要获取%MEM
列的当前值.
Update: I need to get the current value of %MEM
column when executing the top
command in terminal for a specific process.
示例:我需要此函数为VirtualBox进程的进程ID返回14.2.
Example: I need this function to return 14.2 for the process id of VirtualBox process.
推荐答案
使用> c2>
这与top一致.在下面的测试脚本中,您可以将参数更改为定义consume_memory
数组的range函数,该数组仅在此处用于耗尽内存以进行测试,并且python输出和top输出都将匹配:
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()
这篇关于如何获取进程的内存使用率百分比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!