CUDA编程学习(四)

利用Block和Thread进行并行加速

_global_ void add(int *a, int *b, int *c)
{
int index = threadIdx.x + blockIdx.x * blockDim.x;
c[index] = a[index] + b[index];
} #define N (2048*2048)
#define THREAD_PER_BLOCK 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/THREADS_PER_BLOCK,THREADS_PER_BLOCK>>>(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 ;
} /**** What's the function of random_ints****/
void random_ints(int* a, int N)
{
int i;
for (i = ; i < N; ++i)
a[i] = rand();
}
上一篇:一个C#开发搭建Android框架的心路历程


下一篇:为了增强团队的协作和高效开发,提升代码质量,TGideas团队一起制订的代码规范。主要包括五部分内容:PC规范、移动端规范、性能优化、CP规范、其他项目规范