#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,抛出如下异常:
Unhandled exception at 0x773c15de in Resources gormandizer.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0045f864..
1) 为什么这个程序没有填满整个可用内存,尽管它在 64 位操作系统上运行?
2) 为什么只有 26% 的处理器 (intel core i5) 在使用?
最佳答案
如前所述, vector 的元素是连续存储的。此外,根据
std::vector
实现中使用的内存分配算法,它可能会尝试提前预分配内存;分配比用于减少malloc
/new
调用次数更多的内存。因此,它可能会达到要求比 32 位操作系统支持的内存更多的程度(这可以解释为什么 64 位进程可以工作,但 32 位进程不会,尽管有足够的内存可用)。您的进程正在 4 个核心中的一个核心上运行,而且它非常繁忙,因此占用了大约 25% 的 CPU 时间。其他进程将弥补其余部分。
关于c++ - 为什么我的程序设计为耗尽 RAM 和 CPU 而没有使用所有 RAM 和 CPU?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11033442/