從 msdn 摘錄
Collecting Memory Usage Information For a Process
C++:
-
<div>
-
<pre>#include <windows.h>
-
#include <stdio.h>
-
#include "psapi.h"
-
-
void PrintMemoryInfo( DWORD processID )
-
{
-
HANDLE hProcess;
-
PROCESS_MEMORY_COUNTERS pmc;
-
-
// Print the process identifier.
-
-
printf( "\nProcess ID: %u\n", processID );
-
-
// Print information about the memory usage of the process.
-
-
hProcess = OpenProcess( PROCESS_QUERY_INFORMATION
-
PROCESS_VM_READ,
-
FALSE, processID );
-
if (NULL == hProcess)
-
return;
-
-
if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) )
-
{
-
printf( "\tPageFaultCount: 0x%08X\n", pmc.PageFaultCount );
-
printf( "\tPeakWorkingSetSize: 0x%08X\n",
-
pmc.PeakWorkingSetSize );
-
printf( "\tWorkingSetSize: %d K\nn", pmc.WorkingSetSize / 1024 );
-
printf( "\tQuotaPeakPagedPoolUsage: 0x%08X\n",
-
pmc.QuotaPeakPagedPoolUsage );
-
printf( "\tQuotaPagedPoolUsage: 0x%08X\n",
-
pmc.QuotaPagedPoolUsage );
-
printf( "\tQuotaPeakNonPagedPoolUsage: 0x%08X\n",
-
pmc.QuotaPeakNonPagedPoolUsage );
-
printf( "\tQuotaNonPagedPoolUsage: 0x%08X\n",
-
pmc.QuotaNonPagedPoolUsage );
-
printf( "\tPagefileUsage: 0x%08X\n", pmc.PagefileUsage );
-
printf( "\tPeakPagefileUsage: 0x%08X\n",
-
pmc.PeakPagefileUsage );
-
}
-
-
CloseHandle( hProcess );
-
}
-
-
void main( )
-
{
-
// Get the list of process identifiers.
-
-
DWORD aProcesses[1024], cbNeeded, cProcesses, dwCurPID;
-
unsigned int i;
-
-
// 列印目前 process 之記憶體資訊
-
dwCurPID = GetCurrentProcessId();
-
printf("Current process id : %d\n", dwCurPID);
-
PrintMemoryInfo( dwCurPID );
-
-
// 列舉所有的 process id
-
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
-
return;
-
-
// Calculate how many process identifiers were returned.
-
-
cProcesses = cbNeeded / sizeof(DWORD);
-
-
// Print the memory usage for each process
-
-
for ( i = 0; i <cProcesses; i++ )
-
PrintMemoryInfo( aProcesses[i] );
-
}</pre>
-
</div>
其中 PROCESS_MEMORY_COUNTERS 結構成員 WorkingSetSize 除以 1024 所得到的數值,就和我們在工作管理員看到的記憶體使用量一樣。編譯程式需要 psapi.h 及 psapi.lib,這兩個檔案可在vc6用的 2001.Oct msdn 找到。