比较推送数据(100 万个数字)是否事先调整大小到 std::vector。令我感到有趣的是,我发现后者(没有调整大小)更快,这与预期相反。发生了什么 ?我正在使用 MS VC++ 2017 编译器。
double times = 1000000;
vector<double> vec1;
auto tp_start = chrono::high_resolution_clock::now();
for (double i=0; i < times; i++)
{
vec1.push_back(i);
}
auto lapse = chrono::high_resolution_clock::now() - tp_start;
cout << chrono::duration_cast<chrono::milliseconds>(lapse).count() << " ms : push without prior resize \n"; // 501 ms
vector<double> vec2;
vec2.resize(times); // resizing
tp_start = chrono::high_resolution_clock::now();
for (double i = 0; i < times; i++)
{
vec2[i] = i; //fastest
// vec2.push_back(i); //slower
}
lapse = chrono::high_resolution_clock::now() - tp_start;
cout << chrono::duration_cast<chrono::milliseconds>(lapse).count() << " ms : push with prior resizing \n"; // 518 ms , shouldn't this be faster theoritically
已编辑:
修改后:vec2.resize(times);它工作得更快
修改后:vec2.reserve(times);它工作得更快
修改后:vec2[i] = i;变得 super 快
任何建议什么是最佳实践?
已编辑 2(优化模式下的编译器)
1000万数据:
120ms : 41ms reserve & pushback
121ms : 35ms resize & vec[i]
亿数据:
1356ms : 427ms reserve & pushback
1345ms : 364ms resize & vec[i]
vec[i] 仍然获胜
最佳答案
After this change: vec2.resize(times); it works faster
我想这可能是因为在 resize
之后 vec2
实际上拥有 2*times
空间,所以它不需要在以后重新分配 push_back
。
After this change: vec2.reserve(times); it works even faster
这个版本不需要重新分配,所以比第一个好。
After this change: vec2[i] = i; becomes super fast
直接将元素放到它的位置上,与push_back
相比没有多余的操作
原始答案
你应该这样做:
vector<double> vec2;
vec2.resize(sizeof(double)* times); // this directly chage the size(),with capacity() also changed.
tp_start = chrono::high_resolution_clock::now();
for (double i = 0; i < times; i++)
{
vec2[i]=i;//not push_back
}
如果你在这种情况下仍然使用push_back
,它没有任何效率。
在你的resize
例子中,vec2
的大小比vec1
大,需要更多的时间来重新分配它的内存,并且push_back
需要更多时间。顺便说一句,在您的情况下最好执行 reserve(n)
。
关于c++ - 比较在 std::vector 中有和没有事先调整大小的推送数据(100 万个数字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49714729/