EvoTalk

28 七月, 2006

Get Processes Memory Usage

Posted by: asd In: C++| Code Snippet| 程式設計 ()

從 msdn 摘錄

Collecting Memory Usage Information For a Process
C++:
  1. <div>
  2. <pre>#include &lt;windows.h&gt;
  3. #include &lt;stdio.h&gt;
  4. #include "psapi.h"
  5.  
  6. void PrintMemoryInfo( DWORD processID )
  7. {
  8.     HANDLE hProcess;
  9.     PROCESS_MEMORY_COUNTERS pmc;
  10.  
  11.     // Print the process identifier.
  12.  
  13.     printf( "\nProcess ID: %u\n", processID );
  14.  
  15.     // Print information about the memory usage of the process.
  16.  
  17.     hProcess = OpenProcess(  PROCESS_QUERY_INFORMATION
  18.                                     PROCESS_VM_READ,
  19.                                     FALSE, processID );
  20.     if (NULL == hProcess)
  21.         return;
  22.  
  23.     if ( GetProcessMemoryInfo( hProcess, &amp;pmc, sizeof(pmc)) )
  24.     {
  25.         printf( "\tPageFaultCount: 0x%08X\n", pmc.PageFaultCount );
  26.         printf( "\tPeakWorkingSetSize: 0x%08X\n",
  27.                   pmc.PeakWorkingSetSize );
  28.         printf( "\tWorkingSetSize: %d K\nn", pmc.WorkingSetSize / 1024 );
  29.         printf( "\tQuotaPeakPagedPoolUsage: 0x%08X\n",
  30.                   pmc.QuotaPeakPagedPoolUsage );
  31.         printf( "\tQuotaPagedPoolUsage: 0x%08X\n",
  32.                   pmc.QuotaPagedPoolUsage );
  33.         printf( "\tQuotaPeakNonPagedPoolUsage: 0x%08X\n",
  34.                   pmc.QuotaPeakNonPagedPoolUsage );
  35.         printf( "\tQuotaNonPagedPoolUsage: 0x%08X\n",
  36.                   pmc.QuotaNonPagedPoolUsage );
  37.         printf( "\tPagefileUsage: 0x%08X\n", pmc.PagefileUsage );
  38.         printf( "\tPeakPagefileUsage: 0x%08X\n",
  39.                   pmc.PeakPagefileUsage );
  40.     }
  41.  
  42.     CloseHandle( hProcess );
  43. }
  44.  
  45. void main( )
  46. {
  47.     // Get the list of process identifiers.
  48.  
  49.     DWORD aProcesses[1024], cbNeeded, cProcesses, dwCurPID;
  50.     unsigned int i;
  51.    
  52.     // 列印目前 process 之記憶體資訊
  53.     dwCurPID = GetCurrentProcessId();
  54.     printf("Current process id : %d\n", dwCurPID);
  55.     PrintMemoryInfo( dwCurPID );
  56.  
  57.     // 列舉所有的 process id
  58.     if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &amp;cbNeeded ) )
  59.         return;
  60.    
  61.     // Calculate how many process identifiers were returned.
  62.  
  63.     cProcesses = cbNeeded / sizeof(DWORD);
  64.  
  65.     // Print the memory usage for each process
  66.  
  67.     for ( i = 0; i &lt;cProcesses; i++ )
  68.         PrintMemoryInfo( aProcesses[i] );
  69. }</pre>
  70. </div>

其中 PROCESS_MEMORY_COUNTERS 結構成員 WorkingSetSize 除以 1024 所得到的數值,就和我們在工作管理員看到的記憶體使用量一樣。編譯程式需要 psapi.h 及 psapi.lib,這兩個檔案可在vc6用的 2001.Oct msdn 找到。

Tags: ,

Releated Posts



No Responses to "Get Processes Memory Usage"

Comment Form