在 C++ Win32 应用程序中,如何确定私有字节、工作集和虚拟大小[重复]

2024-04-22

我正在编写一些用于教育目的的代码,我希望能够从用 C++ 编写的 Windows 控制台程序中打印这些内存使用值。


花了一些时间从这些链接中获取我想要的内容,但它就是这样。 (大部分困难是让它在 Mingw32 中工作。)

// -*- compile-command:"g++ mem.cpp -lpsapi -g -o mem.exe"; -*-

// Shows the memory: private bytes, working set and virtual size for a process 

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

// MingW32 doesn't have this struct in psapi.h
typedef struct _PROCESS_MEMORY_COUNTERS_EX {
  DWORD  cb;
  DWORD  PageFaultCount;
  SIZE_T PeakWorkingSetSize;
  SIZE_T WorkingSetSize;
  SIZE_T QuotaPeakPagedPoolUsage;
  SIZE_T QuotaPagedPoolUsage;
  SIZE_T QuotaPeakNonPagedPoolUsage;
  SIZE_T QuotaNonPagedPoolUsage;
  SIZE_T PagefileUsage;
  SIZE_T PeakPagefileUsage;
  SIZE_T PrivateUsage;
}PROCESS_MEMORY_COUNTERS_EX, *PPROCESS_MEMORY_COUNTERS_EX;

void PrintMemoryInfo( DWORD processID )
{
    HANDLE hProcess;
    PROCESS_MEMORY_COUNTERS_EX 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, (PROCESS_MEMORY_COUNTERS *) &pmc, sizeof(pmc)) )
    {
        printf( "\tWorkingSetSize: %u\n", pmc.WorkingSetSize );
        printf( "\tPrivate Bytes: %u\n", pmc.PrivateUsage );
        printf( "\tPagefile (peak): %u (%u)\n", pmc.PagefileUsage, pmc.PeakPagefileUsage  );

    }

    CloseHandle( hProcess );
}


int main()
{
    DWORD id = GetCurrentProcessId();

    PrintMemoryInfo(id);

    return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C++ Win32 应用程序中,如何确定私有字节、工作集和虚拟大小[重复] 的相关文章

随机推荐