簡體   English   中英

如何在C ++中獲取Windows下的內存使用率

[英]How to get memory usage under Windows in C++

我試圖找出我的應用程序在程序本身內消耗了多少內存。 我正在尋找的內存使用量是Windows任務管理器的“進程”選項卡上“內存使用情況”列中報告的數量。

一個很好的起點是GetProcessMemoryInfo ,它報告有關指定進程的各種內存信息。 您可以將GetCurrentProcess()作為進程句柄傳遞,以獲取有關調用進程的信息。

可能PROCESS_MEMORY_COUNTERSWorkingSetSize成員是與任務管理器中的Mem Usage coulmn最接近的匹配,但它不會完全相同。 我會嘗試不同的值來找到最符合您需求的值。

我認為這就是你要找的東西:

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


}

GetProcessMemoryInfo是您正在尋找的功能。 MSDN上的文檔將指出您正確的方向。 從傳入的PROCESS_MEMORY_COUNTERS結構中獲取所需的信息。

你需要包含psapi.h。

試試看GetProcessMemoryInfo 我沒有使用它,但它看起來像你需要的。

為了補充Ronin的答案,我們使用函數GlobalMemoryStatusEx為您提供了正確的計數器來獲取調用進程的虛擬內存使用情況:只需從ullTotalVirtual ullAvailVirtual以獲取分配的虛擬內存。 你可以使用ProcessExplorer或其他東西來檢查這個。

令人困惑的是,系統調用GlobalMemoryStatusEx不幸地具有混合目的:它提供系統范圍和特定於進程的信息,例如虛擬內存信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM