簡體   English   中英

malloc函數極限測試

[英]malloc function limit test

我剛剛了解了堆和堆棧內存分配,並且很好奇我可以在堆上分配多少。 正如我所看到的,堆分配提供了指向內存的指針,其中請求的連續字節量是空閑的。 所以我編寫了以下代碼來對我可以分配的最大數量進行二分搜索。

#include <iostream>
#include <chrono>
#include <cassert>
using namespace std;

int main ( void ) {

  size_t lo = 0, hi = -1ll; hi >>= 1; // i am doing this to avoid overflow.
  while (lo + 1 != hi) {
    char * ptr = NULL;
    ptr = (char*) malloc((lo+hi)>>1);
    if (ptr != NULL) lo = (lo+hi)>>1;
    else hi = (lo+hi)>>1;
    free(ptr);
  }

  cout << lo << " is amount of bytes of memory that we could allocate on this system's heap.\n";
  cout << (lo>>10) << " KB\n";
  cout << (lo>>20) << " MB\n";
  cout << (lo>>30) << " GB\n";

  // additional code.
  // this part is to read and write at n uniformly distant cells in 20GB of memory.

  auto start = chrono::high_resolution_clock::now();
  int * arr = (int *) malloc(5ll<<32); // 20GB
  bool ok = true;
  const int n = 10; // n means 5 * 2 ^ n cells to write and read.
  for (long long i=0; i<(5<<n); ++i) {
    assert((5ll<<30) > (i<<(30-n)));
    arr[i << (30-n)] = 23;
    ok &= arr[i << (30-n)] == 23;
  }
  auto end = chrono::high_resolution_clock::now();
  long long elapsed = chrono::duration_cast<chrono::milliseconds>(end - start).count();

  cout << "Elapsed time : " << elapsed << "ms\n";
  cout << (ok ? "ok is True\n" : "ok is False\n");
  
  free(arr);

  return 0;
}

輸出

27672117247 is amount of bytes of memory that we could allocate on this system's heap.
27023551 KB
26390 MB
25 GB
Elapsed time : 13ms
ok is True

我知道輸出會隨着時間在同一台機器上改變。 但我沒想到它總是在 ~22GB 左右,當我的系統的 RAM 容量只有 8GB 時。 這里發生了什么 ?

當我的系統 RAM 容量只有 8GB 時,我沒想到它總是在 ~22GB 左右。 這里發生了什么 ?

大多數現代操作系統使用Virtual Memory ,它允許操作系統從多個來源獲取內存,同時對應用程序隱藏這些細節。 在這種情況下,當您的 8GB RAM 耗盡時,操作系統可能會使用硬盤驅動器上的可用空間。

還有一種觀點是,虛擬內存可以作為單獨的任務進行保留和物理分配。 這允許分配的內存在實際需要之前不會浪費物理存儲空間。 您的代碼沒有使用它分配的內存。 您可能會預留 22GB,但實際上並未提交 22GB 的存儲空間。

暫無
暫無

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

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