我想知道我的Python应用程序的内存使用情况,并且特别想知道哪些代码块/部分或对象占用了大部分内存.Google搜索显示商业广告是Python Memory Validator(仅限Windows).
我没有尝试任何人,所以我想知道哪一个是最好的考虑:
提供大部分细节.
我必须对代码进行最少或不做任何更改.
我写了大约50个类,用于连接和使用机械化和线程的网站.它们都同时工作,但它们并不相互依赖.所以这意味着1个类 - 1个网站 - 1个线程.它不是特别优雅的解决方案,特别是对于管理代码,因为很多代码在每个类中重复(但不足以使它成为一个类来传递参数,因为一些站点可能需要在方法中间对检索到的数据进行额外处理 - 像'登录' - 其他人可能不需要).正如我所说,它并不优雅 - 但它有效.毋庸置疑,我欢迎所有建议如何更好地编写这个,而不使用每个网站方法的1个类.添加每个类的附加功能或整体代码管理是一项艰巨的任务.
但是,我发现,每个线程占用大约8MB内存,因此使用50个正在运行的线程,我们正在考虑大约400MB的使用量.如果它在我的系统上运行我就不会有问题,但由于它在仅有1GB内存的VPS上运行,因此它开始出现问题.你能告诉我如何减少内存使用量,还是有其他方法同时使用多个站点?
我使用这个快速测试python程序来测试它是存储在我的应用程序的变量中的数据是使用内存还是其他东西.正如您在下面的代码中看到的,它只处理sleep()函数,但每个线程使用8MB内存.
from thread import start_new_thread
from time import sleep
def sleeper():
try:
while 1:
sleep(10000)
except:
if running: raise
def test():
global running
n = 0
running = True
try:
while 1:
start_new_thread(sleeper, ())
n += 1
if not (n % 50):
print n
except Exception, e:
running = False
print 'Exception raised:', e
print 'Biggest number of threads:', n
if __name__ == '__main__':
test()
Run Code Online (Sandbox Code Playgroud)
当我运行它时,输出是:
50
100 …Run Code Online (Sandbox Code Playgroud) 我的主要目标是了解我的 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, …Run Code Online (Sandbox Code Playgroud)