다음을 통해 공유


프로세스에 대한 메모리 사용량 정보 수집

애플리케이션의 효율성을 확인하려면 해당 메모리 사용량을 검사할 수 있습니다. 다음 샘플 코드는 GetProcessMemoryInfo 함수를 사용하여 프로세스의 메모리 사용량에 대한 정보를 가져옵니다.

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

// To ensure correct resolution of symbols, add Psapi.lib to TARGETLIBS
// and compile with -DPSAPI_VERSION=1

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: 0x%08X\n", pmc.WorkingSetSize );
        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 );
}

int main( void )
{
    // Get the list of process identifiers.

    DWORD aProcesses[1024], cbNeeded, cProcesses;
    unsigned int i;

    if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
    {
        return 1;
    }

    // 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] );
    }

    return 0;
}

기본 함수는 EnumProcesses 함수를 사용하여 프로세스 목록을 가져옵니다. 각 프로세스에 대해 기본 PrintMemoryInfo 함수를 호출하여 프로세스 식별자를 전달합니다. PrintMemoryInfo는 OpenProcess 함수를 호출하여 프로세스 핸들을 가져옵니다. OpenProcess가 실패하면 출력에는 프로세스 식별자만 표시됩니다. 예를 들어 유휴 및 CSRSS 프로세스에 대해 OpenProcess 는 액세스 제한으로 인해 사용자 수준 코드가 열리지 않으므로 실패합니다. 마지막으로 PrintMemoryInfo는 GetProcessMemoryInfo 함수를 호출하여 메모리 사용량 정보를 가져옵니다.