1

I am interested in monitoring memory usage for a process, much like in the Task Manager, given the process ID on windwos platform. After reading this question and answers and reading up on the PROCESS_MEMORY_COUNTERS I was able to come up with the following:

#include <windows.h>
#include <stdio.h>
#include <psapi.h>
#include <iostream>

SIZE_T getMemoryUsage(DWORD Process_PID) {
  MEMORYSTATUSEX memInfo;
  memInfo.dwLength = sizeof(MEMORYSTATUSEX);
  GlobalMemoryStatusEx(&memInfo);

  PROCESS_MEMORY_COUNTERS PMC;
  HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |PROCESS_VM_READ, FALSE, Process_PID);
  GetProcessMemoryInfo(hProcess, (PROCESS_MEMORY_COUNTERS *)&PMC, sizeof(PMC));

  SIZE_T physicalMemUsedByProc = PMC.WorkingSetSize;

  return physicalMemUsedByProc;
}

However, it only measures Working Set, while what is shown in Task Manager as memory is Private Working set. My question is how can I obtain the Private Working set value if I have Working Set one? Is using PROCESS_MEMORY_COUTNERS a good approach, or should I consider something else for this problem?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Euchidna
  • 11
  • 1
  • https://stackoverflow.com/a/560476/920069 You need to pass a `PROCESS_MEMORY_COUNTERS_EX` struct. – Retired Ninja Sep 02 '22 at 05:59
  • Don't tag C++ questions with the C tag unless you really like downvotes. – Jonathan Leffler Sep 02 '22 at 06:09
  • Hello. Thank you for taking time to answer. Can you please explain a little bit more in details? I am fairly inexperienced in C++, especially when it comes to windows related stuff. I tried something akin to that in order to get PrivateUsage statistic from PROCESS_MEMORY_COUNTERS_EX struct, but the value still doesn't match what I could see in Task Manger. – Euchidna Sep 02 '22 at 06:12
  • I don't know how Task Manager reports memory usage. I just linked the answer that showed how to get the additional stat. You might get something closer using Performance Counters, or not. *shrug* – Retired Ninja Sep 02 '22 at 19:39

0 Answers0