[Tutor] Question about the memory manager

eryk sun eryksun at gmail.com
Wed Jan 13 05:31:58 EST 2016


On Wed, Jan 13, 2016 at 2:01 AM, Albert-Jan Roskam
<sjeik_appie at hotmail.com> wrote:
> I sometimes check the Task Manager to see how much RAM is in use. Is there a Python way to do something similar?

Use the psutil module to solve this problem across platforms. For
Windows only, you can use ctypes to call GetProcessMemoryInfo. Here's
a function that returns the total working set size (including shared
pages) and the private working set.

    import ctypes
    from ctypes import wintypes
    import collections

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

    wintypes.SIZE_T = ctypes.c_size_t

    class PROCESS_MEMORY_COUNTERS(ctypes.Structure):
        _fields_ = (('cb',                         wintypes.DWORD),
                    ('PageFaultCount',             wintypes.DWORD),
                    ('PeakWorkingSetSize',         wintypes.SIZE_T),
                    ('WorkingSetSize',             wintypes.SIZE_T),
                    ('QuotaPeakPagedPoolUsage',    wintypes.SIZE_T),
                    ('QuotaPagedPoolUsage',        wintypes.SIZE_T),
                    ('QuotaPeakNonPagedPoolUsage', wintypes.SIZE_T),
                    ('QuotaNonPagedPoolUsage',     wintypes.SIZE_T),
                    ('PagefileUsage',              wintypes.SIZE_T),
                    ('PeakPagefileUsage',          wintypes.SIZE_T))
        def __init__(self, *args, **kwds):
            super(PROCESS_MEMORY_COUNTERS, self).__init__(*args, **kwds)
            self.cb = ctypes.sizeof(self)

    class PROCESS_MEMORY_COUNTERS_EX(PROCESS_MEMORY_COUNTERS):
        _fields_ = (('PrivateUsage', wintypes.SIZE_T),)

    PPROCESS_MEMORY_COUNTERS = ctypes.POINTER(PROCESS_MEMORY_COUNTERS)

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

    kernel32.GetCurrentProcess.restype = wintypes.HANDLE

    psapi.GetProcessMemoryInfo.errcheck = check_bool
    psapi.GetProcessMemoryInfo.argtypes = (wintypes.HANDLE,
                                           PPROCESS_MEMORY_COUNTERS,
                                           wintypes.DWORD)

    MemoryUsage = collections.namedtuple('MemoryUsage', 'total private')

    def get_memory_usage():
        info = PROCESS_MEMORY_COUNTERS_EX()
        psapi.GetProcessMemoryInfo(kernel32.GetCurrentProcess(),
                                   ctypes.byref(info),
                                   ctypes.sizeof(info))
        if info.PrivateUsage:
            return MemoryUsage(info.WorkingSetSize, info.PrivateUsage)
        else:
            # prior to Windows 7.
            return MemoryUsage(info.WorkingSetSize, info.PagefileUsage)


More information about the Tutor mailing list