构造大尺寸的vector <int>

Tem*_*mak 2 c++ macos memory-management vector

我在OS X 10.9.3,2.4 GHz Intel Core i5,8 GB DDR3上运行以下代码

a.cpp

int main() {
  vector<int> expectation(10e8, -1.0);
  cout << "size()=" << expectation.size() << endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

b.cpp

int main() {
  vector<int> expectation(10e9, -1.0);
  cout << "size()=" << expectation.size() << endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

-

$ time ./a.out 
size()=1000000000

real    0m3.935s
user    0m1.530s
sys 0m2.103s

$ time ./b.out 
size()=10000000000

real    4m49.853s
user    0m16.186s
sys     0m22.966s
Run Code Online (Sandbox Code Playgroud)

在b.pp中,我们有10倍大的向量.
我想知道,为什么在情况下,时间b情况下的约100倍变得比大的情况下一个

UPD
我找到了,我迷失了!
10e8 = 10 ^ 9 int = 4 GB
10e9 = 10 ^ 10 int = 40 GB

Mik*_*our 7

假设每个4字节int,第一个使用4GB内存,并适合你8GB的RAM.第二个使用40GB,需要保持交换到磁盘.那会慢得多.

请注意,这10e9意味着10x10 9或10 10.你可能认为它意味着10 9,它适合RAM.那就是1e9.

  • @Enor:看最后一句话.您的测试是10 ^ 9和10 ^ 10整数. (6认同)