什么是更安全有效的“新 std::complex"?或“fftw_malloc"? [英] What is safer and efficient "new std::complex" or "fftw_malloc"?

查看:36
本文介绍了什么是更安全有效的“新 std::complex"?或“fftw_malloc"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的库采用由 fftw_malloc 分配的指针,但我的数据为 std::complex*.

I'm using a library that takes pointers allocated with fftw_malloc, but my data comes as std::complex<double>*.

什么是最有效的分配和释放内存?

What's the most efficient to allocate and release memory?

#include <fftw3.h>
#include <iostream>

int main()
{
    std::complex<double> * p1, *p2;
    std::vector< complex<double> > v;
    int N=10;

    //Allocating memory 
    p1 = (std::complex<double> *) fftw_malloc( sizeof(std::complex<double>) * N);
    p2 = new std::complex<double>[N];
    v.reserve(N);

    //Do some stuff
    manipulate(p1);
    manipulate(p2);
    manipulate(v.data());

    //Freeing memory 
    fftw_free(p1);
    delete[] p2;

}

既然应该避免强制转换,我们能说p2p1更安全吗?

Given that casting should be avoided, can we say that p2 is safer than p1?

推荐答案

来自 http://fftw.org/fftw3_doc/SIMD-alignment-and-fftw_005fmalloc.html#SIMD-alignment-and-fftw_005fmalloc 你应该使用 FFTW 的分配例程,因为它们提供了具体对齐方式.如果您不使用它们的例程(或不保证对齐),那么您必须使用相同的缓冲区来创建和执行计划.使用他们的例程可以实现更好的矢量化,从而更快地编写代码.

From http://fftw.org/fftw3_doc/SIMD-alignment-and-fftw_005fmalloc.html#SIMD-alignment-and-fftw_005fmalloc you should use FFTW's allocation routines, as they provide a specific alignment. If you don't use their routines (or don't guarantee alignment) then you must use the same buffer for plan creation and execution. Using their routines allows for better vectorization and therefore faster code.

一种解决方案是使用 FFTW++(http://fftwpp.sf.net),它包装了 FFTW用于 C++ 并提供一个内置对齐的 Array 类.否则,您可以创建一个对齐的分配器类,该类将为您提供具有正确对齐的 std::vectors.例如,

One solution is to use FFTW++ (http://fftwpp.sf.net), which wraps FFTW for C++ and provides an Array class which has alignment built-in. Otherwise, you can create an aligned allocator class which will give you std::vectors with the proper alignment. For example,

template<typename Tdata>
class fftw_allocator : public std::allocator<Tdata>
{
public:
    template <typename U>
    struct rebind { typedef fftw_allocator<U> other; };
    Tdata* allocate(size_t n) { return (Tdata*) fftw_malloc(sizeof(Tdata) * n); }
    void deallocate(Tdata* data, std::size_t size) { fftw_free(data); }
};

std::vector<std::complex<double>, fftw_allocator<std::complex<double> > > f(n);

然后您的向量 f 将使用 FFTW 的分配函数分配和释放内存.

Then your vector f will allocate and free memory using FFTW's allocation functions.

这篇关于什么是更安全有效的“新 std::complex"?或“fftw_malloc"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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