#include <iostream>
#include <cassert>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <Windows.h>
using namespace std;
char randomLetter()
{
srand(time(0));
char rValue;
while(1)
if((rValue=(rand()/129)) > 31)
return rValue;
}
int main()
{
vector<char> meegaString;
for(int i=0; i < 10000000000; i++)
{
meegaString.push_back(randomLetter());
if(!(i%10000000))
cout<<"There are: " <<i+1<<" chars in the list"<<endl;
}
system("pause");
return 0;
}
运行此程序之前的RAM使用量约为2500/8000 MB。
当涉及到3200时,将引发以下异常:
1)尽管该程序在64位OS上运行,但为什么它没有填满整个可用内存?
2)为什么仅使用26%的处理器(英特尔酷睿i5)?
最佳答案
std::vector
的实现中使用的内存分配算法,它可能会尝试提前分配内存。分配的内存比减少malloc
/new
调用的数量要多。这样一来,它可能会请求更多的内存,而不是32位操作系统可以支持的内存(这将解释为什么尽管有足够的内存,但64位进程可以工作,而32位进程却无法工作)可用的)。 另请参阅:Being Smart About Vector Memory Allocation
关于c++ - 为什么我的程序设计为不占用RAM和CPU的所有内存和CPU?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11033442/