CUDA编程学习(一)

时间:2022-12-11 06:23:42
/****c code****/
#include<stdio.h> int main()
{
printf("Hello world!\n);
return ;
} /****CUDA code****/ _global_ void mykernel(void)
{
} int main()
{
mykernel<<<,>>>();
printf("Hello world!\n");
return ;
}

1: _global_ 这个符号代表这个函数是在GPU里面跑的

2: mykernel<<<1,1>>>() Also called a "kernel launch"

/**** Add two integers****/

_global_ void add(int *a, int *b, int *c);
{
*c = *a + *b;
} 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 = sizeof(int); //Allocate space for device copies of a, b, c
cudaMalloc((void **)&d_a, size);
cudaMalloc((void **)&d_b, size);
cudaMalloc((void **)&d_c, size); //Setup input values
a = ;
b = ; //Cope inputs to device cudaMemcpy(d_a, &a, size, cudaMemcpyHostToDevice);
cudaMemcpy(d_b, &b, size, cudaMemcpyHostToDevice); //Launch add() kernel on GPU
add<<<,>>>(d_a, d_b, d_c); //Copy result back to host
cudaMemcpy(&c, d_c, size, cudaMemcpyDeviceToHost); //Cleanup
cudaFree(d_a); cudaFree(d_b); cudaFree(d_c);
return ;
}