Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

optimization - C++ 4d array memory deallocation is slow

My code has a 4D matrix in it for some math problem solving

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;

The sizes are very large WidthColumns = 2018, HeightLines = 1332, W_SIZE =7, the memory allocation is very fast but the memory deallocation (delete) is very slow.
Is there a way to optimize it?
I tired openMP but it throws unrelated errors of missing DLL which are there... if I removed the #pragma omp parallel for everything works fine. but slow...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using a pointer to a pointer to... is a bad idea because it will fragment your data a lot.

I would create a class ta manage the indices transform and use 1D array, it's a bit more complicated but it will be faster.

Anyway, a trick: nothing prevent you to build your int**** with pointers to a zone in memory that isn't sparse (1D array you preallocated) and then use it as a 4D array.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...