1

Why after hide (minimize) the window the memory used of program is reduced?

example.py:

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

after run in cmd (Windows XP, Python 2.7.9), used memory in task manager = 4 384 KB. after minimize console window used memory = 1 544 KB

Why is this happening? How to fix memory without hide window?

UPD: Solution: http://blog.in-orde.nl/content/memory-leak-using-com-objects-python-and-how-fix-it

7
  • What exactly do you mean by 'hide'? Minimize? Commented Aug 6, 2015 at 9:28
  • Where did this information come from, and why is it important to you to minimzeyour memory usage, please? Commented Aug 6, 2015 at 9:28
  • tobifasc, yes minimize Commented Aug 6, 2015 at 9:30
  • 1
    Minimizing the window trims the number of pages in the process working set. You can do this programmatically via SetProcessWorkingSetSize. Commented Aug 6, 2015 at 9:39
  • 1
    You may prefer a ctypes solution that doesn't depend on PyWin32: 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). Commented Aug 6, 2015 at 9:58

1 Answer 1

2

Minimizing the window trims the number of pages in the process working set. You can do this programmatically via SetProcessWorkingSetSize. Here's an example using 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)
Sign up to request clarification or add additional context in comments.

1 Comment

This is very helpful. Would you be able to provide an example of how this could be used in the context of a Python script? I am attempting to query a very large dataset from a SQL server in a Windows environment using Python, without using 100% of the system's memory. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.