如何找到 Python 进程及其所有 fork 子进程使用的常驻内存总量?
我知道我可以使用 psutil
,例如,查找当前进程使用的可用物理内存的百分比,如下所示:
import os
import psutil
current_process = psutil.Process(os.getpid())
mem = current_process.memory_percent()
但我正在寻找一个进程及其子进程使用的总内存(如果有的话)。
最佳答案
您可以使用 psutil.Process.children()
(或 psutil.Process.get_children()
旧 psutil 版本)的结果来获取所有子进程和遍历它们。
它可能看起来像:
import os
import psutil
current_process = psutil.Process(os.getpid())
mem = current_process.memory_percent()
for child in current_process.children(recursive=True):
mem += child.memory_percent()
这将汇总主进程、其子进程(分支)和任何子进程的子进程(如果您使用 recursive=True
)使用的内存百分比。您可以在 current psutil docs 中找到此功能或 old docs .
如果您使用的 psutil 版本早于 2,则必须使用 get_children()
而不是 children()
。
关于python - 查找 Python 进程及其所有子进程使用的总内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24494493/