C 4D数组内存Deallocation速度很慢

C++ 4d array memory deallocation is slow

本文关键字:速度 Deallocation 内存 4D 数组      更新时间:2023-10-16

我的代码中有一个4D矩阵,用于某些数学问题求解

int**** Sads = new int***[inputImage->HeightLines];
for (size_t i = 0; i < inputImage->HeightLines; i++)
{
    Sads[i] = new int**[inputImage->WidthColumns];
    for (size_t j = 0; j < inputImage->WidthColumns; j++)
    {
        Sads[i][j] = new int*[W_SIZE];
        for (size_t k = 0; k < W_SIZE; k++)
         {
              Sads[i][j][k] = new int[W_SIZE];
         }
    }
 }
//do something with Sads...
for (int i = 0; i < inputImage->HeightLines; i++)
        {
            int*** tempI = Sads[i];
            for (int j = 0; j < inputImage->WidthColumns; j++)
            {
                int** tempJ = tempI[j];
                for (int k = 0; k < W_SIZE; k++)
                {
                    delete[] tempJ[k];
                }
                delete[] Sads[i][j];
            }
            delete[] Sads[i];
        }
        delete[] Sads;

尺寸非常大的宽度columns = 2018,高度= 1332,w_size = 7,内存分配非常快,但是内存DealLocation(删除)非常慢。
有没有办法优化它?
我疲倦了OpenMP,但它会丢弃缺少DLL的错误错误...如果我删除了#pragma op compallal for Aftery的效果很好。但是慢...

使用指向指针的指针是一个坏主意,因为它会大大散布您的数据。

我会创建一个类Ta的ta管理索引变换和使用1D数组,它更复杂,但会更快。

无论如何,一个技巧:没有什么可以阻止您用指针构建int ****的记忆区域中的区域,该区域不是稀疏的(您已列出的一维数组),然后将其用作4D数组。

我可能倾向于使用 std::vector。现在,记忆分配是为我照顾的(在一个分配/DealLocation中),我获得了免费的副本/移动语义。

我要做的就是提供偏移计算:

#include <vector>
#include <cstddef>
struct vector4
{
    vector4(std::size_t lines, std::size_t columns)
            : lines_(lines), columns_(columns)
    , storage_(totalSize())
    {}
    auto totalSize() const -> std::size_t
    {
        return lines_ * columns_ * w_size * w_size;
    }
    int* at(std::size_t a)
    {
        return storage_.data() + (a * columns_ * w_size * w_size);
    }
    int* at(std::size_t a, std::size_t b)
    {
        return at(a) + (b * w_size * w_size);
    }
    int* at(std::size_t a, std::size_t b, std::size_t c)
    {
        return at(a, b) + (c * w_size);
    }
    int& at(std::size_t a, std::size_t b, std::size_t c, std::size_t d)
    {
        return *(at(a, b, c) + d);
    }
private:
    std::size_t lines_, columns_;
    static constexpr std::size_t w_size = 32; // ?
    std::vector<int> storage_;
};
int main()
{
    auto v = vector4(20, 20);
    v.at(3, 2, 5, 1) = 6;
    // other things
    // now let it go out of scope
}

创建,使用和删除4D数组的正确方法是这样,使用语句组的闭合来删除自动变量。

{
    const int H = 10;
    const int I = 10;
    const int J = 10;
    const int K = 10;
    int h = 0;
    int i = 0;
    int j = 0;
    int k = 0;
    int fourDimArray [H][I][J][K];
    fourDimArray[h][i][j][k] = 0;
}

如果您需要动态分配,请使用STL的列表或向量类别或使用Inline方法的类似内容来计算4D数组索引的1D数组索引,如果您需要倍增速度。

int * fourDimArrayAsOneDim = new int[H*I*J*K];
fourDimArrayAsOneDim[indexFromIndices(h, i, j, k)] = 0;
delete [] fourDimArrayAsOneDim;