【发布时间】:2019-12-07 23:26:21
【问题描述】:
我尝试在堆和堆栈内存中为 10^7 个整数分配空间,以查看哪个更快。显然在堆内存中分配要快得多,但我不明白原因。
#include <bits/stdc++.h>
#include <chrono>
using namespace std;
using namespace std::chrono;
int main()
{
high_resolution_clock::time_point t1 = high_resolution_clock::now();
int *p = new int[1e7];
high_resolution_clock::time_point t2 = high_resolution_clock::now();
auto duration = duration_cast<microseconds>( t2 - t1 ).count();
cout << duration / 1e6 << "\n"; // 5e-06
t1 = high_resolution_clock::now();
vector<int> v(1e7);
t2 = high_resolution_clock::now();
duration = duration_cast<microseconds>( t2 - t1 ).count();
cout << duration / 1e6 << "\n"; // 0.112284
return 0;
}
【问题讨论】:
-
你认为你在堆栈上为 10^7 个整数分配了空间吗?
-
@ReticulatedSpline 但是,在您尝试写入之前,操作系统实际上不会保留该内存。 这是 Linux(以及其他一些操作系统)的“功能” ) 如果您重视系统稳定性,可以禁用它。
-
std::vector也在堆上分配它的数据!只有少数成员变量,包括指针,实际上驻留在堆栈上;试试sizeof(std::vector<int>),给出实际分配在堆栈上的字节数...
标签: c++ performance heap-memory stack-memory