如何在C++中获取Windows下的内存使用率

Bri*_*art 44 c++ windows memory-management

我试图找出我的应用程序在程序本身内消耗了多少内存.我正在寻找的内存使用量是Windows任务管理器的"进程"选项卡上"内存使用情况"列中报告的数量.

Cha*_*lie 46

一个很好的起点是GetProcessMemoryInfo,它报告有关指定进程的各种内存信息.您可以GetCurrentProcess()作为进程句柄传递,以获取有关调用进程的信息.

可能是任务管理器中与Mem Usage coulmn最接近的WorkingSetSize成员PROCESS_MEMORY_COUNTERS,但它不会完全相同.我会尝试不同的值来找到最符合您需求的值.


Ron*_*nin 19

我认为这就是你要找的东西:

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

// Use to convert bytes to MB
#define DIV 1048576

// Use to convert bytes to MB
//#define DIV 1024

// Specify the width of the field in which to print the numbers. 
// The asterisk in the format specifier "%*I64d" takes an integer 
// argument and uses it to pad and right justify the number.

#define WIDTH 7

void _tmain()
{
  MEMORYSTATUSEX statex;

  statex.dwLength = sizeof (statex);

  GlobalMemoryStatusEx (&statex);


  _tprintf (TEXT("There is  %*ld percent of memory in use.\n"),WIDTH, statex.dwMemoryLoad);
  _tprintf (TEXT("There are %*I64d total Mbytes of physical memory.\n"),WIDTH,statex.ullTotalPhys/DIV);
  _tprintf (TEXT("There are %*I64d free Mbytes of physical memory.\n"),WIDTH, statex.ullAvailPhys/DIV);
  _tprintf (TEXT("There are %*I64d total Mbytes of paging file.\n"),WIDTH, statex.ullTotalPageFile/DIV);
  _tprintf (TEXT("There are %*I64d free Mbytes of paging file.\n"),WIDTH, statex.ullAvailPageFile/DIV);
  _tprintf (TEXT("There are %*I64d total Mbytes of virtual memory.\n"),WIDTH, statex.ullTotalVirtual/DIV);
  _tprintf (TEXT("There are %*I64d free Mbytes of virtual memory.\n"),WIDTH, statex.ullAvailVirtual/DIV);
  _tprintf (TEXT("There are %*I64d free Mbytes of extended memory.\n"),WIDTH, statex.ullAvailExtendedVirtual/DIV);


}
Run Code Online (Sandbox Code Playgroud)

  • 它可能不是他想知道的,因为这会测量系统内存的使用,而不是单个进程消耗的内存.但是,知道也可能有用,所以我不会低估它. (4认同)
  • 来源:http://msdn.microsoft.com/en-us/library/windows/desktop/aa366589%28v=vs.85%29.aspx (2认同)

小智 8

GetProcessMemoryInfo是您正在寻找的功能.MSDN上的文档将指出您正确的方向.从传入的PROCESS_MEMORY_COUNTERS结构中获取所需的信息.

你需要包含psapi.h.


Mar*_*som 7

试试看GetProcessMemoryInfo.我没有使用它,但它看起来像你需要的.


Ari*_*ing 6

为了配合由罗宁的回答,indead功能GlobalMemoryStatusEx为您提供了正确的计数器导出的虚拟内存使用情况调用过程:刚。减去ullAvailVirtualullTotalVirtual获得分配的虚拟内存。您可以使用 ProcessExplorer 或其他工具自行检查。

GlobalMemoryStatusEx不幸的是,系统调用具有混合用途,这一点令人困惑:它提供系统范围和进程特定的信息,例如虚拟内存信息。