Tuesday, January 6, 2009

[VC++] Memory info with GetProcessMemoryInfo()

If you need to know the memory usage information of a process programmatically for some tracing purpose or for debugging purpose you can use GetProcessMemoryInfo() API. This API retrieves information about the memory usage of the specified process. Following are the memory statics of a process returned,
PageFaultCount
PeakWorkingSetSize
WorkingSetSize
QuotaPeakPagedPoolUsage
QuotaPagedPoolUsage
QuotaPeakNonPagedPoolUsage
QuotaNonPagedPoolUsage
PagefileUsage
PeakPagefileUsage


Below code snippet will show how to use the same for displaying the memory statics Page File Usage(VM Size) and Peak Page File Usage of the current process in Kilo Bytes. you can use the same logic for other counters also.

#include "psapi.h"
.......
.......
PPROCESS_MEMORY_COUNTERS pMemCountr = new PROCESS_MEMORY_COUNTERS;
if( GetProcessMemoryInfo(GetCurrentProcess(),pMemCountr, sizeof(PROCESS_MEMORY_COUNTERS)))
{
CString csMsg;
csMsg.Format(" PagefileUsage = %uK\n PeakPagefileUsage = %uK", pMemCountr->PagefileUsage/1024, pMemCountr->PeakPagefileUsage/1024 );
MessageBox( csMsg, "Process Memory Information" );
}
delete pMemCountr;

Output Message Box may look something like this for a simple dialog based application,



Please note that this API is declared in the psapi.h so you may need to include the same and need to link to psapi.lib.

No comments: