我在c ++中遇到了std :: vector的内存问题。这是我的代码:
#include <iostream>
#include <vector>
int main () {
std::vector< std::vector<float> > mesh_points_A;
int N=10;
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
std::vector<float> xyz;
xyz.push_back(i);
xyz.push_back(j);
xyz.push_back(0.3);
mesh_points_A.push_back(xyz);
}
}
return 0;
}
当我将N增加到10000或更高时,我的内存耗尽...但我认为我做了一些完全错误的事情,因为如果我想使用带有numpy数组的python,这将很容易......
提前谢谢了。
编辑:这是原始代码。上面的代码只是一个简化,以更好地举例说明问题。问题是,如果以某种方式可以创建许多Surface对象(在代码中当前有两个),而不会耗尽内存,同时保持N = 10000。
// classes example compile with c++ -o Surface Surface.cpp -std=c++11
#include <iostream>
#include <vector>
#include <array>
class Surface {
private:
std::vector< std::array<float,3> > mesh_points_A;
public:
float R;
float z; // z position if the suface
int n_A; //number of area mesh points mesh_points_A.size()
Surface(int nxA, float R , float z);
};
Surface::Surface(int nxA, float R,float z)
: z(z)
, R(R)
{
float dxA= 2*R/(nxA*1.0-1.0);
//determine n_A,
n_A=0;
for(int i=0;i<nxA;i++){
float x = -R+i*dxA;
for(int j=0;j<nxA;j++){
float y = -R+j*dxA;
if(x*x+y*y<R*R){
n_A+=1;
}
}
}
std::cout<<"Number of area mesh points: "<<n_A<<std::endl;
mesh_points_A.reserve(n_A);
for(int i=0;i<nxA;i++){
float x = -R+i*dxA;
for(int j=0;j<nxA;j++){
float y = -R+j*dxA;
if(x*x+y*y<R*R){
std::array<float,3> xyz{ {x,y,z} };
mesh_points_A.push_back(xyz);
}
}
}
}
int main () {
int N= 20000;
Surface s1(N,0.1,0.0);
Surface s2(N,0.1,0.1);
return 0;
}
您的向量需要连续重新分配更多内存以保持增长。它通过保留一个新的,更大的内存区域并复制旧数据来实现这一点。这取决于实现保留多少内存,但典型的策略是分配两倍的内存(libstdc ++这样做)。
这意味着,在最坏的情况下,您的总内存需求可能接近原始内存要求的三倍:
假设您的矢量目前拥有90,000,000个元素,其容量 - 运气不佳 - 也是90,000,0001。要插入90,000,001个元素,std::vector
现在保留两倍的内存 - 180,000,000,复制所有旧元素,然后破坏旧数组。
因此,即使您“只”需要100,000,000个元素,您只需要为270,000,000个元素分配存储空间。这相当于大约9.10 GiB,即使您的100M矢量仅需要3.35 GiB。
通过将以下行放在嵌套初始化循环前面可以巧妙地避免这种情况:
mesh_points_A.reserve(N * N);
1更现实地说,容量可能是2的幂,例如226 = 67,108,864;调整大小仍然是6.75 GiB的内存。
std::vector
具有根据您的需求动态改变大小的灵活性。一如既往,灵活性是有代价的。通常这个价格很小,很容易被忽略,但在这种情况下,当你使用std::vector<float>
vs std::array<float,3>
时差异是非常重要的,因为你有1亿个元素。例如,如果我们运行此代码:
std::vector<float> v;
for( auto f : { 1.0, 2.0, 3.0 } ) v.push_back(f);
std::cout << sizeof(v) << "-" << v.capacity() << std::endl;
std::cout << sizeof(std::array<float,3>) << std::endl;
我们可以看到,在这个平台上,std::vector<float>
本身需要24个字节加上它动态分配4个浮点数的内存 - 16个字节而不是3个浮点数 - 如果您使用固定大小结构则为12个字节。所以在你的情况下差异将是:
1 std::vector - ( 24 + 16 ) * 100 000 000 = 4 000 000 000
2 std::array - 12 * 100 000 000 = 1 200 000 000
2 800 000 000或大约2Gb的内存。
但这不是它的结尾std::vector
有另一个价格 - 它必须在连续空间分配所有数据。通常,当尺寸达到当前尺寸时,重新分配容量。在这种情况下,这意味着创建这些数据的内存需求可以轻松增加一倍以上 - 假设容量达到5000万并且向量需要重新分配,它会创建另一个内存块,比如1亿,同时保留前一个(所以你的记忆必须容纳1.5亿个元素并复制它们。并且没有内存碎片问题。
因此推荐的解决方案是将std::array<float,3>
用于内部数据(或struct
,包含3个元素),并将std::deque
作为外部容器,或者如果必须使用std::vector
,请事先为足够的元素分配内存。