I'm try to monitor the memory usage of a running process using the code below
borrowed from a 2014 post by Flipeador.
Code: Select all
ProcessMemoryInfo(ProcessName) {
ProcessId := InStr(ProcessName, ".")?ProcessExist(ProcessName):ProcessName
, hProcess := DllCall("Kernel32.dll\OpenProcess", "UInt", 0x0010|0x0400, "UInt", 0, "UInt", ProcessId)
, nSize := VarSetCapacity(memCounters, A_PtrSize = 8 ? 72 : 40), NumPut(nSize, memCounters)
if !(DllCall("Psapi.dll\GetProcessMemoryInfo", "Ptr", hProcess, "UInt", &memCounters, "UInt", nSize)) {
memCounters := "", nSize := VarSetCapacity(memCounters, A_PtrSize = 8 ? 80 : 44), NumPut(nSize, memCounters)
if !(DllCall("Kernel32.dll\K32GetProcessMemoryInfo", "Ptr", hProcess, "UInt", &memCounters, "UInt", nSize))
return false, ErrorLevel := true
} i := {}, i.PageFaultCount := NumGet(memCounters, 4, "UInt")
, i.PeakWorkingSetSize := NumGet(memCounters, 8, "Ptr")
, i.WorkingSetSize := NumGet(memCounters, A_PtrSize = 8 ? 16 : 12, "Ptr")
, i.QuotaPeakPagedPoolUsage := NumGet(memCounters, A_PtrSize = 8 ? 24 : 16, "Ptr")
, i.QuotaPagedPoolUsage := NumGet(memCounters, A_PtrSize = 8 ? 32 : 20, "Ptr")
, i.QuotaPeakNonPagedPoolUsage := NumGet( memCounters, A_PtrSize = 8 ? 40 : 24, "Ptr")
, i.QuotaNonPagedPoolUsage := NumGet( memCounters, A_PtrSize = 8 ? 48 : 28, "Ptr")
, i.PagefileUsage := NumGet( memCounters, A_PtrSize = 8 ? 56 : 32, "Ptr")
, i.PeakPagefileUsage := NumGet( memCounters, A_PtrSize = 8 ? 64 : 36, "Ptr")
, i.PrivateUsage := NumGet(memCounters, A_PtrSize = 8 ? 72 : 40, "Ptr")
return i, DllCall("kernel32.dll\CloseHandle", "Ptr", hProcess), ErrorLevel := false
}
Issue 1.
However The the first DllCall {DllCall("Psapi.dll\GetProcessMemoryInfo", "Ptr", hProcess, "UInt", &memCounters, "UInt", nSize)}
always returns True.
Consequently The Kerne32 version is never called and consequently PrivateUsage
is never returned (the PROCESS_MEMORY_COUNTERS structure is only 72 bytes).
I could drop the PSAPI call altogether and call only the Kernel32 version but
on the Microsoft website they recommending using the PSAPI version to ensure
compatibility with older systems.
Issue 2.
If I do call just the Kernel32 version the value returned for private memory
usage does not match the value shown in TaskManager -- but all other
memory usage values do match.
Is there a way to get the same processes private memory usage that TaskManager reports?
Thanks.