【问题标题】:Python program memory in windowsWindows中的Python程序内存
【发布时间】:2015-10-29 08:53:53
【问题描述】:

为什么隐藏(最小化)窗口后程序使用的内存减少了?

example.py:

import time
while True:
    a = 2*2
    a = 0
    time.sleep(0.1)

在 cmd (Windows XP, Python 2.7.9) 中运行后,任务管理器中使用的内存 = 4 384 KB。最小化控制台窗口后使用的内存 = 1 544 KB

为什么会这样? 如何在不隐藏窗口的情况下修复内存?

更新: 解决方案:http://blog.in-orde.nl/content/memory-leak-using-com-objects-python-and-how-fix-it

【问题讨论】:

  • “隐藏”到底是什么意思?最小化?
  • 这些信息是从哪里来的?为什么尽量减少内存使用量对您很重要?
  • tobifasc,是的,最小化
  • 最小化窗口修剪进程工作集中的页数。您可以通过SetProcessWorkingSetSize 以编程方式执行此操作。
  • 您可能更喜欢不依赖 PyWin32 的 ctypes 解决方案:import ctypes;kernel32 = ctypes.WinDLL('kernel32');kernel32.GetCurrentProcess.restype = ctypes.c_void_p;kernel32.SetProcessWorkingSetSize.argtypes = (ctypes.c_void_p, ctypes.c_size_t, ctypes.c_size_t);kernel32.SetProcessWorkingSetSize(kernel32.GetCurrentProcess(), -1, -1)

标签: python windows memory console


【解决方案1】:

最小化窗口会修剪进程工作集中的页数。您可以通过SetProcessWorkingSetSize 以编程方式执行此操作。这是使用 ctypes 的示例:

import ctypes
from ctypes import wintypes

kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

def errcheck_bool(result, func, args):
    if not result:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

kernel32.GetCurrentProcess.restype = wintypes.HANDLE
kernel32.SetProcessWorkingSetSize.errcheck = errcheck_bool
kernel32.SetProcessWorkingSetSize.argtypes = (wintypes.HANDLE,
                                              ctypes.c_size_t,
                                              ctypes.c_size_t)

def trim_working_set():
    hProcess = kernel32.GetCurrentProcess()
    kernel32.SetProcessWorkingSetSize(hProcess, -1, -1)

【讨论】:

  • 这很有帮助。您能否提供一个示例,说明如何在 Python 脚本的上下文中使用它?我正在尝试使用 Python 从 Windows 环境中的 SQL 服务器查询一个非常大的数据集,而不使用 100% 的系统内存。谢谢。
猜你喜欢
  • 2010-10-02
  • 1970-01-01
  • 1970-01-01
  • 2012-02-26
  • 2013-05-14
  • 1970-01-01
  • 2011-04-22
  • 1970-01-01
  • 2014-05-01
相关资源
最近更新 更多