结构体的内存分配(低性能)

Memory allocation for struct (low performance)

本文关键字:性能 分配 内存 结构体      更新时间:2023-10-16

我确实有一个关于为几个结构分配内存的缓慢性能的问题。我有一个结构体,它看起来像下面的

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();

并初始化它之后的元素。不幸的是,这是相当慢,因此,你们谁有一个想法,以提高性能?

首先,您需要修复它,使其实际上是用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
};

其次,为了提高性能,您将需要一个自定义分配器。提振。Pool将是一个不错的选择——它是一个预先存在的解决方案,明确地为相同大小的重复分配而设计,在本例中为sizeof(node)。还有其他方案,如内存竞技场,可以更快,这取决于您的释放需求。

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

node* Nodes = new node[1000000];

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