参考博客:https://blog.csdn.net/weixin_40427089/article/details/86621826
学习资料:《CUDA C编程权威指南》,作者:程润伟(John Cheng),出版社:机械工业出版社
第一章
主要描述了CUDA平台,其性能的一些指标,以及如何写出第一个CUDA程序。
一.CUDA是什么
1.CUDA 是一种通用的并行计算平台和编程模型,它利用NVIDIA GPU中的并行计算引擎能更有效地解决复杂的计算问题.通过使用CUDA,我们可以像在CPU上那样,通过GPU来进行运算.
2.一个 CUDA 程序包含两部分的混合:
①在CPU上运行的代码
②在GPU上运行的代码
二.Hello,world!
//用GPU输出Hello,world!
#include <stdio.h>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
__global__ void hellofromGPU(void)
{
printf("Hello world from GPU! by thread %d\n",threadIdx.x);
}
int main()
{
//hello from CPU
printf("Hello world from CPU!\n");
hellofromGPU <<<1, 10 >>> ();
cudaDeviceReset();
return 0;
}
其中,__global__输出符表示该函数为核函数(kernel function)。核函数即是要进行并行处理的函数。在调用的时候,采用function_name<<<Grid,Block>>>(parameters)的格式进行调用。在这里,线程数没有被指定,也就是1个Block,每个Block里面有10个Thread。
运行结果为:
Hello world from CPU!
Hello world from GPU! by thread 0
Hello world from GPU! by thread 1
Hello world from GPU! by thread 2
Hello world from GPU! by thread 3
Hello world from GPU! by thread 4
Hello world from GPU! by thread 5
Hello world from GPU! by thread 6
Hello world from GPU! by thread 7
Hello world from GPU! by thread 8
Hello world from GPU! by thread 9
在这里可以看到,thread的下标,是从0开始的。
cudaDeviceReset()相当于GPU的清理工作函数,在执行完之后,使用该函数可以释放被占用的DRAM。将设备重置回运行前的状态。
三.CUDA编程结构
一个典型的CUDA编程结构包括 5 个主要的步骤.
1.分配GPU内存
2.从CPU内存中拷贝数据到GPU内存
3.调用CUDA内核函数(kernel)来完成程序指定的运算.
4.将数据从GPU拷回CPU内存.
5.释放GPU内存空间
四.CUDA中的层次结构
1、内存层次机构
2、线程层次结构