Bus*_*ush 5 python windows profiling memory-leaks
我的主要目标是了解我的 python 应用程序在执行过程中占用了多少内存。
我在 Windows-32 和 Windows-64 上使用 python 2.7.5。
我找到了一种方法来获取有关我的进程的一些信息:http ://code.activestate.com/recipes/578513-get-memory-usage-of-windows-processes-using-getpro/
为了方便起见,将代码放在这里:
"""Functions for getting memory usage of Windows processes."""
__all__ = ['get_current_process', 'get_memory_info', 'get_memory_usage']
import ctypes
from ctypes import wintypes
GetCurrentProcess = ctypes.windll.kernel32.GetCurrentProcess
GetCurrentProcess.argtypes = []
GetCurrentProcess.restype = wintypes.HANDLE
SIZE_T = ctypes.c_size_t
class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure):
_fields_ = [
('cb', wintypes.DWORD),
('PageFaultCount', wintypes.DWORD),
('PeakWorkingSetSize', SIZE_T),
('WorkingSetSize', SIZE_T),
('QuotaPeakPagedPoolUsage', SIZE_T),
('QuotaPagedPoolUsage', SIZE_T),
('QuotaPeakNonPagedPoolUsage', SIZE_T),
('QuotaNonPagedPoolUsage', SIZE_T),
('PagefileUsage', SIZE_T),
('PeakPagefileUsage', SIZE_T),
('PrivateUsage', SIZE_T),
]
GetProcessMemoryInfo = ctypes.windll.psapi.GetProcessMemoryInfo
GetProcessMemoryInfo.argtypes = [
wintypes.HANDLE,
ctypes.POINTER(PROCESS_MEMORY_COUNTERS_EX),
wintypes.DWORD,
]
GetProcessMemoryInfo.restype = wintypes.BOOL
def get_current_process():
"""Return handle to current process."""
return GetCurrentProcess()
def get_memory_info(process=None):
"""Return Win32 process memory counters structure as a dict."""
if process is None:
process = get_current_process()
counters = PROCESS_MEMORY_COUNTERS_EX()
ret = GetProcessMemoryInfo(process, ctypes.byref(counters),
ctypes.sizeof(counters))
if not ret:
raise ctypes.WinError()
info = dict((name, getattr(counters, name))
for name, _ in counters._fields_)
return info
def get_memory_usage(process=None):
"""Return this process's memory usage in bytes."""
info = get_memory_info(process=process)
return info['PrivateUsage']
if __name__ == '__main__':
import pprint
pprint.pprint(get_memory_info())
Run Code Online (Sandbox Code Playgroud)
这是结果:
{'PageFaultCount': 1942L,
'PagefileUsage': 4624384L,
'PeakPagefileUsage': 4624384L,
'PeakWorkingSetSize': 7544832L,
'PrivateUsage': 4624384L,
'QuotaNonPagedPoolUsage': 8520L,
'QuotaPagedPoolUsage': 117848L,
'QuotaPeakNonPagedPoolUsage': 8776L,
'QuotaPeakPagedPoolUsage': 117984L,
'WorkingSetSize': 7544832L,
'cb': 44L}
Run Code Online (Sandbox Code Playgroud)
但这并不能令我满意。这些结果为我提供了整个 python 进程信息,而我需要的只是在 Python 框架之上运行的特定应用程序。
我在互联网上和 Stack Overflow 上看到了几个内存分析器,但它们对我来说太大了。我需要的唯一信息是我的应用程序本身消耗了多少内存 - 不考虑所有 Python 框架。
我怎样才能实现这个目标?
这是我用来查找另一个脚本执行期间使用的最大资源量的脚本。我正在使用psutil
来实现这一点。您可以调整脚本以使其适合您的目的。
import psutil, sys
import numpy as np
from time import sleep
pid = int(sys.argv[1])
delay = int(sys.argv[2])
p = psutil.Process(pid)
max_resources_used = -1
while p.is_running():
## p.memory_info()[0] returns 'rss' in Unix
r = int(p.memory_info()[0] / 1048576.0) ## resources used in Mega Bytes
max_resources_used = r if r > max_resources_used else max_resources_used
sleep(delay)
print("Maximum resources used: %s MB." %np.max(max_resources_used))
Run Code Online (Sandbox Code Playgroud)
用法:
python script.py pid delay_in_seconds
Run Code Online (Sandbox Code Playgroud)
例如:
python script.py 55356 2
Run Code Online (Sandbox Code Playgroud)
解释:
您需要找出进程 ID 并将其作为参数传递给脚本,加上检查资源使用情况的时间间隔(以秒为单位)(即脚本每隔多少秒检查已使用的资源量)。该脚本会跟踪内存使用情况,直到进程运行为止。最后它返回已使用的最大内存量(以 MB 为单位)。