cuda资料整理(4)

傅立叶变换—FFT(cuda实现)

背景:

无意间看到cuda解决FFT有一个cufft函数库,大体查看了有关cufft有关知识,写了一个解决一维情况的cuda代码,据调查知道cufft在解决1D,2D,3D的情况时间复杂度都为O(nlogn),附上解决一维情况的代码,准备后面找一些详细的资料去学习一下cuda的函数库。

复制代码
#include "stdio.h"
#include "cuda_runtime.h"
#include "cufft.h"
#include "device_launch_parameters.h"


#define LENGTH 4
int main()
{

float Data[LENGTH] = {1,2,3,4}; cufftComplex *CompData=(cufftComplex*)malloc(LENGTH*sizeof(cufftComplex)); int i; for(i=0;i<LENGTH;i++) { CompData[i].x=Data[i]; CompData[i].y=0; } cufftComplex *d_fftData; cudaMalloc((void**)&d_fftData,LENGTH*sizeof(cufftComplex)); cudaMemcpy(d_fftData,CompData,LENGTH*sizeof(cufftComplex),cudaMemcpyHostToDevice); cufftHandle plan; cufftPlan1d(&plan,LENGTH,CUFFT_C2C,1); cufftExecC2C(plan,(cufftComplex*)d_fftData,(cufftComplex*)d_fftData,CUFFT_FORWARD); cudaDeviceSynchronize(); cudaMemcpy(CompData,d_fftData,LENGTH*sizeof(cufftComplex),cudaMemcpyDeviceToHost); for(i=0;i<LENGTH;i++) { if(CompData[i].x != 0) { printf("%3.1f",CompData[i].x); } if(CompData[i].y != 0 ) { printf("+%3.1fi",CompData[i].y); } printf("\n"); } cufftDestroy(plan); free(CompData); cudaFree(d_fftData); }
复制代码

在Linux下运行的这段代码:

编译命令:nvcc -o fftcu FFT.cu -I /usr/local/cuda/include  -L /usr/local/cuda/lib64 -lcufft

运行命令:./fftcu

注:/usr/local/cuda/include中有cufft.h头文件,/usr/local/cuda/lib64中有libcufft.so库文件

Leave a Reply

Your email address will not be published. Required fields are marked *