码迷,mamicode.com
首页 > 其他好文 > 详细

CUDA编程学习(二)

时间:2014-11-29 11:44:48      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

将数据加载到GPU后,如何在grid下的block进行并行计算(一个grid包含多个block)

/****How do we run code in parallel on the device****/    
/****Use block****/
    
_global_ void add(int *a, int *b, int *c)
{
    c[blockIdx.x] = a[blockIdx.x] + b[blockIdx.x];
}

#define N 512

int main()
{
    int *a, *b, *c;            //host copies of a, b, c
    int *d_a, *d_b, *d_c;    //device copies of a, b, c
    int size = N * sizeof(int);
    
    //Alloc space for device copies of a, b, c
    cudaMalloc((void **)&d_a, size);
    cudaMalloc((void **)&d_b, size);
    cudaMalloc((void **)&d_c, size);
    
    //Alloc space for host copies of a, b, c and setup input values
    a = (int *)malloc(size); random_ints(a, N);
    b = (int *)malloc(size); random_ints(b, N);
    c = (int *)malloc(size); 
    
    //Copy the data into device
    cudeMemcpy(d_a, a, size, cudaMemcpyHostToDevice);
    cudaMemcpy(d_b, b, size, cudaMemcpyHostToDevice);
    
    //Launch add() kernel on GPU with N blocks
    add<<<N,1>>>(d_a, d_b, d_c);
    
    //Copy result back to host
    cudaMemcpy(c, d_c, size, cudaMemcpyDeviceToHost);
    
    //Cleanup
    free(a); free(b); free(c);
    cudeFree(d_a); cudaFree(d_b); cudaFree(d_c);
    return 0;

}


/**** What‘s the function of random_ints****/
void random_ints(int* a, int N)
{
 int i;
 for (i = 0; i < N; ++i)
 a[i] = rand();
}

 

CUDA编程学习(二)

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/lxy2017/p/4130440.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!