C ++ 4D数组内存重新分配很慢 [英] C++ 4d array memory deallocation is slow

查看:96
本文介绍了C ++ 4D数组内存重新分配很慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中包含4D矩阵,用于解决一些数学问题

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;

大小非常大WidthColumns = 2018,HeightLines = 1332,W_SIZE = 7,内存分配非常快,但是内存释放(删除)非常慢.
有没有优化的方法?
我对openMP感到厌倦,但是它抛出了缺少DLL的无关错误……如果我删除了#pragma omp并行文件,一切正常.但是慢...

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...

推荐答案

我可能倾向于使用std::vector.现在,内存分配已由我负责(一次分配/解除分配),并且我获得了自由的复制/移动语义.

I'd probably be inclined to use a std::vector. Now memory allocation is taken care of for me (in one allocation/deallocation) and I get free copy/move semantics.

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

All I have to do is provide the offset calculations:

#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
}

这篇关于C ++ 4D数组内存重新分配很慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆