struct的内存分配(低性能)

时间:2013-03-11 11:58:11

标签: c++ visual-studio-2010 performance memory-management numerical-analysis

我确实有一个问题与为多个结构分配内存的性能降低有关。 我有一个结构看起来像:见下面

typedef struct _node
{
 // Pointer to leaves & neigbours
 struct _node *children[nrChild], *neighb[nrNeigh];
 // Pointer to parent Node
 struct _node *parentNode;  
 struct _edgeCorner *edgePointID[nrOfEdge];

 int    indexID;                // Value
 double f[latDir];              // Lattice Velos
 double rho;                    // Density
 double  Umag;                  // Mag. velocity    
 int    depth;                  // Depth of octree element

} node

在我的代码开头,我必须创建很多(100.000 - 1.000.000) 使用:

tree = new node();

并在其后启动元素。 不幸的是,这是非常慢,因此你们中的任何人都有想法提高性能吗?

2 个答案:

答案 0 :(得分:3)

首先,您需要修复它,以便它实际上是用C ++编写的。

struct node
{
    // Pointer to leaves & neigbours
    std::array<std::unique_ptr<node>, nrChild> children;
    std::array<node*, nrNeigh> neighb;
    // Pointer to parent Node
    node* parentNode;  
    std::array<_edgeCorner*, nrOfEdge> edgePointID;

    int    indexID;                // Value
    std::array<double, latDir> f;  // Lattice Velos
    double rho;                    // Density
    double  Umag;                  // Mag. velocity    
    int    depth;                  // Depth of octree element
};

其次,为了提高性能,您需要一个自定义分配器。 Boost.Pool将是一个很好的选择 - 它是一个预先存在的解决方案,明确设计用于相同大小的重复分配,在本例中为sizeof(节点)。还有其他方案,如记忆竞技场,可以更快,取决于你的释放需求。

答案 1 :(得分:1)

如果你知道你将拥有多少个节点,你可以一次性分配它们:

node* Nodes = new node[1000000];

您需要在之后设置值,就像您逐个进行设置一样。如果以这种方式更快,您可以尝试一种架构,在分配它们之前,您可以找到需要多少节点,即使您现在没有这个数字。