我遇到了一个奇怪的情况.
在我的程序中,我有一个循环,它将一堆数据组合在一个巨大的向量中.我试图找出它运行得如此缓慢的原因,尽管看起来我正在尽一切努力在旅途中以有效的方式分配内存.
在我的程序中,很难确定组合数据的最终向量应该有多大,但是每个数据的大小在处理时都是已知的.因此,我不是一次性保留和调整组合数据向量,而是为每个数据块保留足够的空间,因为它被添加到较大的向量中.那时我遇到了这个问题,可以使用下面的简单片段重复:
std::vector<float> arr1;
std::vector<float> arr2;
std::vector<float> arr3;
std::vector<float> arr4;
int numLoops = 10000;
int numSubloops = 50;
{
// Test 1
// Naive test where no pre-allocation occurs
for (int q = 0; q < numLoops; q++)
{
for (int g = 0; g < numSubloops; g++)
{
arr1.push_back(q * g);
}
}
}
{
// Test 2
// Ideal situation where total amount of data is reserved beforehand
arr2.reserve(numLoops * numSubloops);
for (int …Run Code Online (Sandbox Code Playgroud) inline void add(const DataStruct& rhs) {
using namespace boost::assign;
vec.reserve(vec.size() + 3);
vec += rhs.a, rhs.b, rhs.c;
}
Run Code Online (Sandbox Code Playgroud)
上述功能是为约17000倍执行,其执行(据我可以看到.有一些改造涉及)约2个数量级更差与调用载体::储备.
我总是认为保留可以加速push_back,即使是小值,但这似乎不正确,我找不到任何明显的原因,为什么它不应该这样.保留是否会阻止功能的内联?对size()的调用是否过于昂贵?这取决于平台吗?我会尝试编写一些小基准来在干净的环境中确认这一点.
编译器:gcc (GCC) 4.4.2使用-g -O2
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<int> v;
auto vsize = v.capacity();
for (int tmp = 0; tmp < 1000;tmp++)
{
v.push_back(tmp);
if(vsize!=v.capacity())
{
vsize = v.capacity();
cout << "capacity changed : " << vsize << endl;
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
向量的容量应该是前一倍,为什么MSVC不能在此工作?