c++/cuda并行累计求和

文章目录

  • 代码
  • CMakeLists.txt
  • 结果

代码

#include
#include
//#include
#include

__global__ void kernel(int* arr, int* sumv, const int size){
    for(int index=blockDim.x*blockIdx.x+threadIdx.x;
    index<size; index+=blockDim.x*gridDim.x)
    {
        arr[index] = index+1;
        atomicAdd(sumv,arr[index]);
    }
}

int main()
{
    int size = 5;
    int* arr = new int[size];
    int* sumv = new int;

    int* arrCuda;
    int* sumvCuda;
    cudaMalloc((void**)&arrCuda,size*sizeof(int));
    cudaMalloc((void**)&sumvCuda,1*sizeof(int));

    cudaMemcpy(arrCuda,arr,size*sizeof(int),cudaMemcpyHostToDevice);
    cudaMemcpy(sumvCuda,sumv,1*sizeof(int),cudaMemcpyHostToDevice);
    
    kernel<<<32,128>>>(arrCuda,sumvCuda,size);
    cudaDeviceSynchronize();

    cudaMemcpy(arr,arrCuda,size*sizeof(int),cudaMemcpyDeviceToHost);
    cudaMemcpy(sumv,sumvCuda,1*sizeof(int),cudaMemcpyDeviceToHost);

    for(int i=0;i<size;++i){
        printf("arr[%d]=%d\n",i, arr[i]);
    }
    printf("%d\n",*sumv);

    cudaFree(sumvCuda);
    cudaFree(arrCuda);
    delete sumv;
    delete[] arr;
    return 0;
}

CMakeLists.txt

CMAKE_MINIMUM_REQUIRED(VERSION 3.16)
PROJECT(MyProject LANGUAGES CUDA CXX)

include(CheckLanguage)
check_language(CUDA)

add_executable(out main.cu ${SRC})

结果

c++/cuda并行累计求和_第1张图片

你可能感兴趣的:(cuda编程学习,c++,算法,开发语言)