【问题标题】:How to get memory usage under Windows in C++如何在 C++ 中获取 Windows 下的内存使用情况
【发布时间】:2010-09-21 21:13:17
【问题描述】:

我试图从程序本身中找出我的应用程序消耗了多少内存。我要查找的内存使用情况是 Windows 任务管理器的“进程”选项卡上“内存使用情况”列中报告的数字。

【问题讨论】:

    标签: c++ windows memory-management


    【解决方案1】:

    为了补充 Ronin 的答案,indead 函数 GlobalMemoryStatusEx 为您提供了适当的计数器来得出调用进程的虚拟内存使用情况:只需从 ullTotalVirtual 中减去 ullAvailVirtual 即可获得分配的虚拟内存。您可以使用 ProcessExplorer 或其他工具自行检查。

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

    【讨论】:

    【解决方案2】:

    我想这就是你要找的东西:

    #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);
    
    
    }
    

    【讨论】:

    • 这可能不是他想知道的,因为这衡量的是系统正在使用的内存,而不是单个进程消耗的内存。但是知道它也可能很有用,所以我不会贬低它。
    • 这不是问题的意思,虽然一般来说可能有用。
    【解决方案3】:

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

    可能PROCESS_MEMORY_COUNTERSWorkingSetSize 成员与任务管理器中的Mem Usage 列最接近,但不会完全相同。我会尝试不同的值,以找到最接近您需求的值。

    【讨论】:

      【解决方案4】:

      尝试查看GetProcessMemoryInfo。我没用过,不过看起来是你需要的。

      【讨论】:

        【解决方案5】:

        GetProcessMemoryInfo 是您正在寻找的功能。 MSDN 上的文档将为您指明正确的方向。从您传入的 PROCESS_MEMORY_COUNTERS 结构中获取您想要的信息。

        您需要包含 psapi.h。

        【讨论】:

          猜你喜欢
          • 2012-02-11
          • 2010-10-14
          • 1970-01-01
          • 2013-04-25
          • 2011-01-02
          • 2020-03-07
          • 2019-06-03
          相关资源
          最近更新 更多