问题:Python进程使用的总内存?
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.
回答 0
这是适用于各种操作系统(包括Linux,Windows 7等)的有用解决方案:
import os
import psutil
process = psutil.Process(os.getpid())
print(process.memory_info().rss) # in bytes
在我当前使用psutil 5.6.3安装的python 2.7中,最后一行应为
print(process.memory_info()[0])
相反(API发生了变化)。
注意:pip install psutil
如果尚未安装,请执行此操作。
Here is a useful solution that works for various operating systems, including Linux, Windows, etc.:
import os
import psutil
process = psutil.Process(os.getpid())
print(process.memory_info().rss) # in bytes
With Python 2.7 and psutil 5.6.3, the last line should be
print(process.memory_info()[0])
instead (there was a change in the API later).
Note: do pip install psutil
if it is not installed yet.
回答 1
对于基于Unix的系统(Linux,Mac OS X,Solaris),可以使用getrusage()
标准库模块中的功能resource
。产生的对象具有属性ru_maxrss
,该属性给出了调用过程的峰值内存使用情况:
>>> resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
2656 # peak memory usage (kilobytes on Linux, bytes on OS X)
在Python文档不记单位。请参阅您特定系统的man getrusage.2
页面以检查单位的值。在Ubuntu 18.04上,单位记为千字节。在Mac OS X上,它是字节。
getrusage()
还可以提供该功能resource.RUSAGE_CHILDREN
以获取子进程的使用情况,以及(在某些系统上)resource.RUSAGE_BOTH
总(自身和子)进程的使用情况。
如果你只关心Linux的,则可以选择阅读/proc/self/status
或/proc/self/statm
在其他的答案对这个问题,并描述文件这一个了。
For Unix based systems (Linux, Mac OS X, Solaris), you can use the getrusage()
function from the standard library module resource
. The resulting object has the attribute ru_maxrss
, which gives the peak memory usage for the calling process:
>>> resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
2656 # peak memory usage (kilobytes on Linux, bytes on OS X)
The Python docs don’t make note of the units. Refer to your specific system’s man getrusage.2
page to check the unit for the value. On Ubuntu 18.04, the unit is noted as kilobytes. On Mac OS X, it’s bytes.
The getrusage()
function can also be given resource.RUSAGE_CHILDREN
to get the usage for child processes, and (on some systems) resource.RUSAGE_BOTH
for total (self and child) process usage.
If you care only about Linux, you can alternatively read the /proc/self/status
or /proc/self/statm
file as described in other answers for this question and this one too.
回答 2
在Windows上,您可以使用WMI(主页,Cheeseshop):
def memory():
import os
from wmi import WMI
w = WMI('.')
result = w.query("SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d" % os.getpid())
return int(result[0].WorkingSet)
在Linux上(来自python cookbook http://code.activestate.com/recipes/286222/:
import os
_proc_status = '/proc/%d/status' % os.getpid()
_scale = {'kB': 1024.0, 'mB': 1024.0*1024.0,
'KB': 1024.0, 'MB': 1024.0*1024.0}
def _VmB(VmKey):
'''Private.
'''
global _proc_status, _scale
# get pseudo file /proc/<pid>/status
try:
t = open(_proc_status)
v = t.read()
t.close()
except:
return 0.0 # non-Linux?
# get VmKey line e.g. 'VmRSS: 9999 kB\n ...'
i = v.index(VmKey)
v = v[i:].split(None, 3) # whitespace
if len(v) < 3:
return 0.0 # invalid format?
# convert Vm value to bytes
return float(v[1]) * _scale[v[2]]
def memory(since=0.0):
'''Return memory usage in bytes.
'''
return _VmB('VmSize:') - since
def resident(since=0.0):
'''Return resident memory usage in bytes.
'''
return _VmB('VmRSS:') - since
def stacksize(since=0.0):
'''Return stack size in bytes.
'''
return _VmB('VmStk:') - since
On Windows, you can use WMI (home page, cheeseshop):
def memory():
import os
from wmi import WMI
w = WMI('.')
result = w.query("SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d" % os.getpid())
return int(result[0].WorkingSet)
On Linux (from python cookbook http://code.activestate.com/recipes/286222/:
import os
_proc_status = '/proc/%d/status' % os.getpid()
_scale = {'kB': 1024.0, 'mB': 1024.0*1024.0,
'KB': 1024.0, 'MB': 1024.0*1024.0}
def _VmB(VmKey):
'''Private.
'''
global _proc_status, _scale
# get pseudo file /proc/<pid>/status
try:
t = open(_proc_status)
v = t.read()
t.close()
except:
return 0.0 # non-Linux?
# get VmKey line e.g. 'VmRSS: 9999 kB\n ...'
i = v.index(VmKey)
v = v[i:].split(None, 3) # whitespace
if len(v) < 3:
return 0.0 # invalid format?
# convert Vm value to bytes
return float(v[1]) * _scale[v[2]]
def memory(since=0.0):
'''Return memory usage in bytes.
'''
return _VmB('VmSize:') - since
def resident(since=0.0):
'''Return resident memory usage in bytes.
'''
return _VmB('VmRSS:') - since
def stacksize(since=0.0):
'''Return stack size in bytes.
'''
return _VmB('VmStk:') - since
回答 3
在UNIX上,您可以使用该ps
工具进行监视:
$ ps u -p 1347 | awk '{sum=sum+$6}; END {print sum/1024}'
其中1347是某个进程ID。此外,结果以MB为单位。
On unix, you can use the ps
tool to monitor it:
$ ps u -p 1347 | awk '{sum=sum+$6}; END {print sum/1024}'
where 1347 is some process id. Also, the result is in MB.
回答 4
Linux,Python 2,Python 3和pypy上当前进程的当前内存使用情况,没有任何导入:
def getCurrentMemoryUsage():
''' Memory usage in kB '''
with open('/proc/self/status') as f:
memusage = f.read().split('VmRSS:')[1].split('\n')[0][:-3]
return int(memusage.strip())
在Linux 4.4和4.9上进行了测试,但即使是早期的Linux版本也可以使用。
在文件中man proc
查找信息并进行搜索/proc/$PID/status
,它提到了某些字段的最低版本(例如Linux 2.6.10的“ VmPTE”),但是“ VmRSS”字段(我在这里使用)没有提及。因此,我认为它从早期版本就已经存在。
Current memory usage of the current process on Linux, for Python 2, Python 3, and pypy, without any imports:
def getCurrentMemoryUsage():
''' Memory usage in kB '''
with open('/proc/self/status') as f:
memusage = f.read().split('VmRSS:')[1].split('\n')[0][:-3]
return int(memusage.strip())
It reads the status file of the current process, takes everything after VmRSS:
, then takes everything before the first newline (isolating the value of VmRSS), and finally cuts off the last 3 bytes which are a space and the unit (kB).
To return, it strips any whitespace and returns it as a number.
Tested on Linux 4.4 and 4.9, but even an early Linux version should work: looking in man proc
and searching for the info on the /proc/$PID/status
file, it mentions minimum versions for some fields (like Linux 2.6.10 for “VmPTE”), but the “VmRSS” field (which I use here) has no such mention. Therefore I assume it has been in there since an early version.
回答 5
我喜欢它,谢谢@bayer。我现在有一个特定的过程计数工具。
# Megabyte.
$ ps aux | grep python | awk '{sum=sum+$6}; END {print sum/1024 " MB"}'
87.9492 MB
# Byte.
$ ps aux | grep python | awk '{sum=sum+$6}; END {print sum " KB"}'
90064 KB
附上我的流程清单。
$ ps aux | grep python
root 943 0.0 0.1 53252 9524 ? Ss Aug19 52:01 /usr/bin/python /usr/local/bin/beaver -c /etc/beaver/beaver.conf -l /var/log/beaver.log -P /var/run/beaver.pid
root 950 0.6 0.4 299680 34220 ? Sl Aug19 568:52 /usr/bin/python /usr/local/bin/beaver -c /etc/beaver/beaver.conf -l /var/log/beaver.log -P /var/run/beaver.pid
root 3803 0.2 0.4 315692 36576 ? S 12:43 0:54 /usr/bin/python /usr/local/bin/beaver -c /etc/beaver/beaver.conf -l /var/log/beaver.log -P /var/run/beaver.pid
jonny 23325 0.0 0.1 47460 9076 pts/0 S+ 17:40 0:00 python
jonny 24651 0.0 0.0 13076 924 pts/4 S+ 18:06 0:00 grep python
参考
I like it, thank you for @bayer. I get a specific process count tool, now.
# Megabyte.
$ ps aux | grep python | awk '{sum=sum+$6}; END {print sum/1024 " MB"}'
87.9492 MB
# Byte.
$ ps aux | grep python | awk '{sum=sum+$6}; END {print sum " KB"}'
90064 KB
Attach my process list.
$ ps aux | grep python
root 943 0.0 0.1 53252 9524 ? Ss Aug19 52:01 /usr/bin/python /usr/local/bin/beaver -c /etc/beaver/beaver.conf -l /var/log/beaver.log -P /var/run/beaver.pid
root 950 0.6 0.4 299680 34220 ? Sl Aug19 568:52 /usr/bin/python /usr/local/bin/beaver -c /etc/beaver/beaver.conf -l /var/log/beaver.log -P /var/run/beaver.pid
root 3803 0.2 0.4 315692 36576 ? S 12:43 0:54 /usr/bin/python /usr/local/bin/beaver -c /etc/beaver/beaver.conf -l /var/log/beaver.log -P /var/run/beaver.pid
jonny 23325 0.0 0.1 47460 9076 pts/0 S+ 17:40 0:00 python
jonny 24651 0.0 0.0 13076 924 pts/4 S+ 18:06 0:00 grep python
Reference
回答 6
对于Python 3.6和psutil 5.4.5,更容易使用此处memory_percent()
列出的函数。
import os
import psutil
process = psutil.Process(os.getpid())
print(process.memory_percent())
For Python 3.6 and psutil 5.4.5 it is easier to use memory_percent()
function listed here.
import os
import psutil
process = psutil.Process(os.getpid())
print(process.memory_percent())
回答 7
甚至比/proc/self/status
:更容易使用/proc/self/statm
。这只是几个统计信息之间用空格分隔的列表。我无法判断两个文件是否总是存在。
/ proc / [pid] / statm
提供有关内存使用情况的信息,以页为单位。这些列是:
- 大小(1)程序总大小(与/ proc / [pid] / status中的VmSize相同)
- 常驻(2)常驻集大小(与/ proc / [pid] / status中的VmRSS相同)
- 共享(3)个常驻共享页面(即由文件支持)的数量(与/ proc / [pid] / status中的RssFile + RssShmem相同)
- 文字(4)文字(代码)
- lib(5)库(从Linux 2.6开始不使用;始终为0)
- 数据(6)数据+堆栈
- dt(7)脏页(自Linux 2.6起未使用;始终为0)
这是一个简单的例子:
from pathlib import Path
from resource import getpagesize
PAGESIZE = getpagesize()
PATH = Path('/proc/self/statm')
def get_resident_set_size() -> int:
"""Return the current resident set size in bytes."""
# statm columns are: size resident shared text lib data dt
statm = PATH.read_text()
fields = statm.split()
return int(fields[1]) * PAGESIZE
data = []
start_memory = get_resident_set_size()
for _ in range(10):
data.append('X' * 100000)
print(get_resident_set_size() - start_memory)
生成的列表看起来像这样:
0
0
368640
368640
368640
638976
638976
909312
909312
909312
您可以看到在大约分配了3个100,000字节后,它跳了约300,000字节。
Even easier to use than /proc/self/status
: /proc/self/statm
. It’s just a space delimited list of several statistics. I haven’t been able to tell if both files are always present.
/proc/[pid]/statm
Provides information about memory usage, measured in pages.
The columns are:
- size (1) total program size
(same as VmSize in /proc/[pid]/status)
- resident (2) resident set size
(same as VmRSS in /proc/[pid]/status)
- shared (3) number of resident shared pages (i.e., backed by a file)
(same as RssFile+RssShmem in /proc/[pid]/status)
- text (4) text (code)
- lib (5) library (unused since Linux 2.6; always 0)
- data (6) data + stack
- dt (7) dirty pages (unused since Linux 2.6; always 0)
Here’s a simple example:
from pathlib import Path
from resource import getpagesize
PAGESIZE = getpagesize()
PATH = Path('/proc/self/statm')
def get_resident_set_size() -> int:
"""Return the current resident set size in bytes."""
# statm columns are: size resident shared text lib data dt
statm = PATH.read_text()
fields = statm.split()
return int(fields[1]) * PAGESIZE
data = []
start_memory = get_resident_set_size()
for _ in range(10):
data.append('X' * 100000)
print(get_resident_set_size() - start_memory)
That produces a list that looks something like this:
0
0
368640
368640
368640
638976
638976
909312
909312
909312
You can see that it jumps by about 300,000 bytes after roughly 3 allocations of 100,000 bytes.
回答 8
下面是我的函数装饰器,它可以跟踪该过程在函数调用之前消耗了多少内存,在函数调用之后使用了多少内存以及执行了多长时间。
import time
import os
import psutil
def elapsed_since(start):
return time.strftime("%H:%M:%S", time.gmtime(time.time() - start))
def get_process_memory():
process = psutil.Process(os.getpid())
return process.memory_info().rss
def track(func):
def wrapper(*args, **kwargs):
mem_before = get_process_memory()
start = time.time()
result = func(*args, **kwargs)
elapsed_time = elapsed_since(start)
mem_after = get_process_memory()
print("{}: memory before: {:,}, after: {:,}, consumed: {:,}; exec time: {}".format(
func.__name__,
mem_before, mem_after, mem_after - mem_before,
elapsed_time))
return result
return wrapper
因此,当您用它装饰一些功能时
from utils import track
@track
def list_create(n):
print("inside list create")
return [1] * n
您将能够看到以下输出:
inside list create
list_create: memory before: 45,928,448, after: 46,211,072, consumed: 282,624; exec time: 00:00:00
Below is my function decorator which allows to track how much memory this process consumed before the function call, how much memory it uses after the function call, and how long the function is executed.
import time
import os
import psutil
def elapsed_since(start):
return time.strftime("%H:%M:%S", time.gmtime(time.time() - start))
def get_process_memory():
process = psutil.Process(os.getpid())
return process.memory_info().rss
def track(func):
def wrapper(*args, **kwargs):
mem_before = get_process_memory()
start = time.time()
result = func(*args, **kwargs)
elapsed_time = elapsed_since(start)
mem_after = get_process_memory()
print("{}: memory before: {:,}, after: {:,}, consumed: {:,}; exec time: {}".format(
func.__name__,
mem_before, mem_after, mem_after - mem_before,
elapsed_time))
return result
return wrapper
So, when you have some function decorated with it
from utils import track
@track
def list_create(n):
print("inside list create")
return [1] * n
You will be able to see this output:
inside list create
list_create: memory before: 45,928,448, after: 46,211,072, consumed: 282,624; exec time: 00:00:00
回答 9
import os, win32api, win32con, win32process
han = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION|win32con.PROCESS_VM_READ, 0, os.getpid())
process_memory = int(win32process.GetProcessMemoryInfo(han)['WorkingSetSize'])
import os, win32api, win32con, win32process
han = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION|win32con.PROCESS_VM_READ, 0, os.getpid())
process_memory = int(win32process.GetProcessMemoryInfo(han)['WorkingSetSize'])
回答 10
对于Unix系统time
,如果通过-v,则命令(/ usr / bin / time)会为您提供该信息。参见Maximum resident set size
下文,这是程序执行期间使用的最大(峰值)实际(非虚拟)内存:
$ /usr/bin/time -v ls /
Command being timed: "ls /"
User time (seconds): 0.00
System time (seconds): 0.01
Percent of CPU this job got: 250%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.00
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 0
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 315
Voluntary context switches: 2
Involuntary context switches: 0
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
For Unix systems command time
(/usr/bin/time) gives you that info if you pass -v. See Maximum resident set size
below, which is the maximum (peak) real (not virtual) memory that was used during program execution:
$ /usr/bin/time -v ls /
Command being timed: "ls /"
User time (seconds): 0.00
System time (seconds): 0.01
Percent of CPU this job got: 250%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.00
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 0
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 315
Voluntary context switches: 2
Involuntary context switches: 0
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
回答 11
使用sh和os来了解python Bayer的答案。
float(sh.awk(sh.ps('u','-p',os.getpid()),'{sum=sum+$6}; END {print sum/1024}'))
答案以兆字节为单位。
Using sh and os to get into python bayer’s answer.
float(sh.awk(sh.ps('u','-p',os.getpid()),'{sum=sum+$6}; END {print sum/1024}'))
Answer is in megabytes.