CUDA 一维卷积实现

来源:互联网 发布:开源小软件 编辑:程序博客网 时间:2024/04/30 01:53

简单实现了在CUDA中的一维卷积

//一维卷积实现__global__ void convolution_1D_basic_kernel(int *N, int *M, int *P,int Mask_Width, int Width){int i = blockIdx.x*blockDim.x + threadIdx.x;float Pvalue = 0;int N_start_point = i - (Mask_Width / 2);for (int j = 0; j < Mask_Width; j++){if(N_start_point + j >= 0 && N_start_point + j < Width){Pvalue += N[N_start_point + j] * M[j];}}P[i] = Pvalue;}int main(){const int M[5] = { 3, 4, 5, 4, 3 };const int N[7] = { 1, 2, 3, 4, 5, 6, 7 };int Mask_Width = 5;int Width = 7;int P[7] = { 0 };int *dev_M = 0;int *dev_N = 0;int *dev_P = 0;//申请内存cudaMalloc((void**)&dev_M, Mask_Width * sizeof(int));cudaMalloc((void**)&dev_N, Width * sizeof(int));cudaMalloc((void**)&dev_P, Width * sizeof(int));cudaMemcpy(dev_M, M, Mask_Width * sizeof(int), cudaMemcpyHostToDevice);cudaMemcpy(dev_N, N, Width * sizeof(int), cudaMemcpyHostToDevice);convolution_1D_basic_kernel <<<1, 7 >>>(dev_N, dev_M, dev_P, Mask_Width,Width);cudaMemcpy(P, dev_P, 7 * sizeof(int), cudaMemcpyDeviceToHost);for (int i = 0; i < 7; i++){cout << P[i] << " ";if (i == 6){cout << endl;}}cudaFree(dev_M);cudaFree(dev_N);cudaFree(dev_P);    return 0;}


0 0
原创粉丝点击