How to get memory usage under Windows in C++

I am trying to find out how much memory my application is consuming from within the program itself. The memory usage I am looking for is the number reported in the "Mem Usage" column on the Processes tab of Windows Task Manager.


Solution 1:

A good starting point would be GetProcessMemoryInfo, which reports various memory info about the specified process. You can pass GetCurrentProcess() as the process handle in order to get information about the calling process.

Probably the WorkingSetSize member of PROCESS_MEMORY_COUNTERS is the closest match to the Mem Usage coulmn in task manager, but it's not going to be exactly the same. I would experiment with the different values to find the one that's closest to your needs.

Solution 2:

I think this is what you were looking for:

#include<windows.h>
#include<stdio.h>   
#include<tchar.h>

// Use to convert bytes to MB
#define DIV 1048576

// Use to convert bytes to MB
//#define DIV 1024

// Specify the width of the field in which to print the numbers. 
// The asterisk in the format specifier "%*I64d" takes an integer 
// argument and uses it to pad and right justify the number.

#define WIDTH 7

void _tmain()
{
  MEMORYSTATUSEX statex;

  statex.dwLength = sizeof (statex);

  GlobalMemoryStatusEx (&statex);


  _tprintf (TEXT("There is  %*ld percent of memory in use.\n"),WIDTH, statex.dwMemoryLoad);
  _tprintf (TEXT("There are %*I64d total Mbytes of physical memory.\n"),WIDTH,statex.ullTotalPhys/DIV);
  _tprintf (TEXT("There are %*I64d free Mbytes of physical memory.\n"),WIDTH, statex.ullAvailPhys/DIV);
  _tprintf (TEXT("There are %*I64d total Mbytes of paging file.\n"),WIDTH, statex.ullTotalPageFile/DIV);
  _tprintf (TEXT("There are %*I64d free Mbytes of paging file.\n"),WIDTH, statex.ullAvailPageFile/DIV);
  _tprintf (TEXT("There are %*I64d total Mbytes of virtual memory.\n"),WIDTH, statex.ullTotalVirtual/DIV);
  _tprintf (TEXT("There are %*I64d free Mbytes of virtual memory.\n"),WIDTH, statex.ullAvailVirtual/DIV);
  _tprintf (TEXT("There are %*I64d free Mbytes of extended memory.\n"),WIDTH, statex.ullAvailExtendedVirtual/DIV);


}

Solution 3:

GetProcessMemoryInfo is the function you are looking for. The docs on MSDN will point you in the right direction. Get the info you want out of the PROCESS_MEMORY_COUNTERS structure you pass in.

You'll need to include psapi.h.