我想了解內存使用情況的兩個細節,以及如何使用C++來測量它。我知道,在Windows下,正在使用的當前應用程序,檢索的RAM數量的快速方法包括<Windows.h>
時,就是:無法使用GetProcessMemoryInfo測量靜態數組的內存使用情況
PROCESS_MEMORY_COUNTERS info;
GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info));
(uint64_t)info.WorkingSetSize;
然後,我用的是運行一個非常簡單的測試:
#include <iostream>
#include <Windows.h>"
int main(void)
{
uint64_t currentUsedRAM(0);
PROCESS_MEMORY_COUNTERS info;
GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info));
currentUsedRAM = info.WorkingSetSize;
const int N(1000000);
int x[N]; //in the second run, comment this line out
int y[N]; //in the second run, comment this line out
//int *x = new int[N]; //in the second run UNcomment this line out
//int *y = new int[N]; //in the second run UNcomment this line out
for (int i = 0; i < N; i++)
{
x[i] = 1;
y[i] = 2;
}
GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info));
currentUsedRAM = info.WorkingSetSize - currentUsedRAM;
std::cout << "Current RAM used: " << currentUsedRAM << "\n";
return 0;
}
當我運行上面的代碼時,輸出結果是:Current RAM used: 0
,而我期待8mb左右的數據,因爲我填充了兩個每個有100萬條記錄的1D int
數組。現在,如果我重新運行代碼,但使x
和y
成爲dinamically分配的陣列,現在輸出如預期:Current RAM used: 8007680
。
這是爲什麼?如何在兩種情況下檢測內存使用情況?
我很驚訝你的程序甚至開始,因爲你爲這兩個數組分配了近8兆內存。 Windows上的默認堆棧大小通常是一個MB。有了這個,你也應該知道你爲什麼沒有得到預期的結果。 –
@Someprogrammerdude這完全是**我的疑問。我的直覺正是這個函數只是測量堆中的內存分配,而不是堆棧中的內存分配。但是,由於應用程序運行,我無法理解發生了什麼。所以,這只是該函數只能獲得堆內存使用。有沒有辦法計算堆棧內存使用情況? –
編譯已經優化了這兩個數組。你可以做一些副作用來防止這種情況:嘗試輸出他們元素的總和。 – felix