ITQuants blog

How to check the memory used on a C++ process?

Feb 14

Written by:
2/14/2013 5:26 PM  RssIcon

When developing an executable, there are several solutions to follow the memory consumption on a process. A third party performance monitor could be used in order to store the information and follow the memory growth on the time. I know some like Sysload, provided by Orsyp.

Another solution is to dump the memory used at different steps of the process in some log files and using this log files to make some statistics.

 The question is also the following: in a C++ Win32 process, how to get the memory used by the system and by the process?

For the system, the function GlobalMemoryStatus permits to get the available memory on the whole OS. The function is defined in the Win32 psapi header file, it means psapi.h, provided with every installation of Visual Studio for example. Concerning the process memory consumption, GetProcessMemoryinfo has to be used. It is defined in the psapi.h header file too. When these functions are used in the excutable, psapi.lib has to be added in the input files of the linker.

Using these methods, some code could look like this one:

01.#include "stdafx.h"
02.#include
03.#include
04. 
05. 
06.int _tmain(int argc, _TCHAR* argv[])
07.{
08. 
09.    MEMORYSTATUS stat;
10.    GlobalMemoryStatus( &stat );
11.    std::stringstream str;
12.    str << "MEM USAGE: TotalPage: " << stat.dwTotalPageFile/1024/1024 << " MB ";
13.    str << "FreePage: " << stat.dwAvailPageFile/1024/1024 << " MB ";
14.    str << "TotalPhy: " << stat.dwTotalPhys/1024/1024 << " MB ";
15.    str << "FreePhy: " << stat.dwAvailPhys/1024/1024 << " MB ";
16.    str << "TotalUserPage: " << stat.dwTotalVirtual/1024/1024 << " MB ";
17.    str << "FreeUserPage: " << stat.dwAvailVirtual/1024/1024 << " MB ";
18.    str << std::endl;
19. 
20.    PROCESS_MEMORY_COUNTERS pmc;
21.    if(GetProcessMemoryInfo( GetCurrentProcess(), &pmc, sizeof( pmc ) ))
22.    {
23.            str << "MEM USAGE: ";
24.            str << " PeakWSS: " << pmc.PeakWorkingSetSize / 1024 << " KB ";
25.            str << " WSS: "     << pmc.WorkingSetSize / 1024    << " KB ";
26.            str << " PFU: "      << pmc.PagefileUsage / 1024     << " KB ";
27.            str << " PeakPFU: "  << pmc.PeakPagefileUsage / 1024 << " KB "  << std::endl;
28.    }

Search blog