Python进程使用的总内存? [英] Total memory used by Python process?
问题描述
Python程序是否有办法确定当前正在使用多少内存?我已经看到了有关单个对象的内存使用情况的讨论,但是我需要的是该过程的总内存使用情况,以便可以确定何时需要开始丢弃缓存的数据.
Is there a way for a Python program to determine how much memory it's currently using? I've seen discussions about memory usage for a single object, but what I need is total memory usage for the process, so that I can determine when it's necessary to start discarding cached data.
推荐答案
Here is a useful solution that works for various operating systems, including Linux, Windows 7, etc.:
import os
import psutil
process = psutil.Process(os.getpid())
print(process.memory_info().rss) # in bytes
在我当前使用psutil 5.6.3安装的python 2.7中,最后一行应该是
On my current Python 2.7 install with psutil 5.6.3, the last line should be
print(process.memory_info()[0])
相反(API有所更改).
instead (there was a change in the API).
注意:如果尚未安装,请执行pip install psutil
.
Note: do pip install psutil
if it is not installed yet.
这篇关于Python进程使用的总内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!