python - 获取python应用程序内存使用情况

标签 python windows memory-leaks profiling

我的主要目标是了解我的 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())

这是结果:

{'PageFaultCount': 1942L,
 'PagefileUsage': 4624384L,
 'PeakPagefileUsage': 4624384L,
 'PeakWorkingSetSize': 7544832L,
 'PrivateUsage': 4624384L,
 'QuotaNonPagedPoolUsage': 8520L,
 'QuotaPagedPoolUsage': 117848L,
 'QuotaPeakNonPagedPoolUsage': 8776L,
 'QuotaPeakPagedPoolUsage': 117984L,
 'WorkingSetSize': 7544832L,
 'cb': 44L}

但这并不能让我满意。这些结果为我提供了整个 Python 进程信息,而我只需要在 Python 框架之上运行的特定应用程序。

我在互联网上和 Stack Overflow 上看到了几个内存分析器,但它们对我来说太大了。我需要的唯一信息是我的应用程序本身消耗了多少内存——无需考虑所有 Python 框架。

我怎样才能做到这一点?

最佳答案

这是一个简单易行的 pythonic 方式,基于 (os, psutil) 模块。感谢 (Dataman) 和 (RichieHindle) 的回答。

import os
import psutil


## - Get Process Id of This Running Script -
proc_id = os.getpid()

print '\nProcess ID: ', proc_id


#--------------------------------------------------
## - Get More Info Using the Process Id

ObjInf = psutil.Process(proc_id)

print '\nProcess %s Info:' % proc_id, ObjInf

#--------------------------------------------------
## - Proccess Name of this program 

name = ObjInf.name()

print '\nThis Program Process name:', name

#--------------------------------------------------
## - Print CPU Percentage

CpuPerc = ObjInf.cpu_percent()

print '\nCpu Percentage:', CpuPerc


#---------------------------------------------------
## - Print Memory Usage

memory_inf = ObjInf.memory_full_info()

print '\nMemory Info:', memory_inf, '\n'



## Print available commands you can do with the psutil obj

for c in dir(ObjInf):
    print c 

如果你的脚本是用 python 编写的,那么你的脚本就是 python 本身,所以没有它它就不会运行,因此你还必须考虑 python 内存使用情况,如果你想看看 python 本身消耗了多少内存只需运行一个空的 python 脚本,您将从那里推断出,您的脚本将是主要的资源使用者,它恰好是用 python 制作的,因此是 python。

现在,如果您想检查线程的内存使用情况,那么这个问题可能会有所帮助 -> Why does python thread consume so much memory?

关于python - 获取python应用程序内存使用情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17754512/

相关文章:

file - 如何在 Linux 中查找哪个进程正在泄漏文件句柄?

python - 命名实体识别: How to tag the training set and chose the algorithm?

使用 selenium 在 Sauce Lab 上进行 Android 测试

c++ - 交叉编译——Windows 上的 V8 和 Linux

windows - Emacs + 史莱姆 + SBCL ( Windows )

python - 如何在 python 中获取 Windows 用户的全名?

c++ - LeakSanitizer 和泄漏库

python - 不允许执行 Sudo pip install 升级操作

python - 用于查找阶乘的 Python 代码的问题

objective-c - 仪器(分配)并找出哪些对象会产生问题