代码之家  ›  专栏  ›  技术社区  ›  Brian Stewart

如何在C++中实现Windows下的内存使用

  •  42
  • Brian Stewart  · 技术社区  · 17 年前

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

    5 回复  |  直到 17 年前
        1
  •  56
  •   hmjd    14 年前

    一个好的起点是 GetProcessMemoryInfo ,它报告有关指定进程的各种内存信息。你可以通过 GetCurrentProcess()

    可能是 WorkingSetSize PROCESS_MEMORY_COUNTERS

        2
  •  24
  •   Andreas Haferburg    11 年前

    我想这就是你想要的:

    #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
  •  8
  •   Adzm Adzm    17 年前

    GetProcessMemoryInfo是您正在寻找的函数。MSDN上的文档将为您指明正确的方向。从传入的进程\内存\计数器结构中获取所需信息。

    你需要包括psapi.h。

        4
  •  7
  •   Mark Ransom    17 年前

    GetProcessMemoryInfo . 我没用过,但看起来像是你需要的。

        5
  •  6
  •   Yunus King    8 年前

    GlobalMemoryStatusEx 为您提供正确的计数器,以导出调用进程的虚拟内存使用情况:只需减法 ullAvailVirtual 从…起 ullTotalVirtual

    系统调用 GlobalMemoryStatusEx 不幸的是,它的用途是混合的:它同时提供系统范围和进程特定的信息,例如虚拟内存信息。