第三章 CUDA C簡介
代碼地址:
ZhangXinNan/CUDA-by-Example-source-code-for-the-book-s-examples-
3.2 第一個程序
3.2.1 hello world
代碼:hello_world.cu
- 主機(host):CPU及系統的內存稱爲主機。
- 設備(device):GPU及其內存稱爲設備。
- 核函數(kernel):GPU上運行的函數稱爲核函數。
3.2.2 核函數調用
代碼:simple_kernel.cu
__global__ :告訴編譯器,函數應該編譯爲在設備而不是在主機上運行。
3.2.3 傳遞參數
代碼:simple_kernel_params.cu
- cudaMolloc() CUDA運行時在設備上分配內存
- cudaFree() 釋放cudaMolloc()分配的內存
- cudaMemcpy() 訪問設備上的內存
【注】
(1)不能爲主機代碼中使用cudaMalloc()分配的指針進行內存讀寫操作。
(2)主機指針只能訪問主機代碼中的內存,設備指針只能訪問設備代碼中的內存。
3.3 查詢設備
代碼:enum_gpu.cu
- cudaGetDeviceCount() 獲得CUDA設備的數量。
- cudaDeviceProp 結構體,設備的相關屬性。
- cudaGetDeviceProperties() 查詢設備的相關信息
輸出:
--- General Information for device 0 ---
Name: GeForce GTX 1070
Compute capability: 6.1
Clock rate: 1695000
Device copy overlap: Enabled
Kernel execution timeout : Enabled
--- Memory Information for device 0 ---
Total global mem: 0
Total constant Mem: 65536
Max mem pitch: 2147483647
Texture Alignment: 512
--- MP Information for device 0 ---
Multiprocessor count: 16
Shared mem per mp: 49152
Registers per mp: 65536
Threads in warp: 32
Max threads per block: 1024
Max thread dimensions: (1024, 1024, 64)
Max grid dimensions: (2147483647, 65535, 65535)
3.4 設備屬性的使用
代碼:set_gpu.cu
輸出:
ID of current CUDA device: 0
ID of CUDA device closest to revision 1.3: 0
- cudaChooseDevice() 選擇滿足條件的某個設備
- cudaSetDevice() 所有的設備操作執行在這個設備上。