you will say goodbye to girls if you are saying “hello world”. 碼猿有風險,入行需謹慎
第一個CUDA程序
參考《GPGPU編程技術——從GLSL、CUDA到OpenCL》的4.3節第一個CUDA程序,因爲版本的不同所以對原書的代碼進行修改。
修改後的代碼
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
__global__ void my_first_kernel(float *x)
{
int i = threadIdx.x + blockDim.x * blockIdx.x;
*(x + i) = (float) threadIdx.x;
}
int main(int argc, char **argv)
{
float *pfCPU = NULL;
float *pfGPU = NULL;
int nBlocks, nThreads, nSize, n;
// 設置block數、每個block的線程數
nBlocks = 2;
nThreads = 8;
nSize = nBlocks * nThreads;
// 分配CPU和GPU存儲空間
pfCPU = (float *)malloc(nSize * sizeof(float));
cudaMalloc((void **)&pfGPU, nSize * sizeof(float));
// 數據初始化
memset(pfCPU, 0, nSize * sizeof(float));
cudaMemset(pfGPU, 0, nSize * sizeof(float));
// 執行全局函數
my_first_kernel<<< nBlocks, nThreads >>>(pfGPU);
// 取回計算結果,並打印輸出
cudaMemcpy(pfCPU, pfGPU, nSize * sizeof(float), cudaMemcpyDeviceToHost);
for (n = 0; n < nSize; n++)
{
printf("%d %f \n", n, *(pfCPU + n));
}
// 回收存儲空間
cudaFree(pfGPU);
free(pfCPU);
return 0;
}
代碼分析
1) CUDA 初始化設備時默認使用0號設備,也可以通過 cudaSetDevice() 函數來啓動其它GPU設備。
2) malloc() 分配內存空間
3) cudaMalloc() 分配顯存空間
4) memset() 初始化內存空間
5) cudaMemset() 初始化顯存空間
6) 限定符 __global__ 表示全局函數,從主機調用,在設備裏執行。
7) cudaMemcpy() 將處理結果複製到目的內存。
8) free() 以及 cudaFree() 分別釋放內存和顯存的空間。
CUDA提供的demo
新建 CUDA Runtime的時候,會提供一個demo。當然比第一個嚴謹規範。
代碼
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdio.h>
cudaError_t addWithCuda(int *c, const int *a, const int *b, unsigned int size);
__global__ void addKernel(int *c, const int *a, const int *b)
{
int i = threadIdx.x;
c[i] = a[i] + b[i];
}
int main()
{
const int arraySize = 5;
const int a[arraySize] = { 1, 2, 3, 4, 5 };
const int b[arraySize] = { 10, 20, 30, 40, 50 };
int c[arraySize] = { 0 };
// Add vectors in parallel.
cudaError_t cudaStatus = addWithCuda(c, a, b, arraySize);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "addWithCuda failed!");
return 1;
}
printf("{1,2,3,4,5} + {10,20,30,40,50} = {%d,%d,%d,%d,%d}\n",
c[0], c[1], c[2], c[3], c[4]);
// cudaDeviceReset must be called before exiting in order for profiling and
// tracing tools such as Nsight and Visual Profiler to show complete traces.
cudaStatus = cudaDeviceReset();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceReset failed!");
return 1;
}
return 0;
}
// Helper function for using CUDA to add vectors in parallel.
cudaError_t addWithCuda(int *c, const int *a, const int *b, unsigned int size)
{
int *dev_a = 0;
int *dev_b = 0;
int *dev_c = 0;
cudaError_t cudaStatus;
// Choose which GPU to run on, change this on a multi-GPU system.
cudaStatus = cudaSetDevice(0);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaSetDevice failed! Do you have a CUDA-capable GPU installed?");
goto Error;
}
// Allocate GPU buffers for three vectors (two input, one output) .
cudaStatus = cudaMalloc((void**)&dev_c, size * sizeof(int));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMalloc failed!");
goto Error;
}
cudaStatus = cudaMalloc((void**)&dev_a, size * sizeof(int));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMalloc failed!");
goto Error;
}
cudaStatus = cudaMalloc((void**)&dev_b, size * sizeof(int));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMalloc failed!");
goto Error;
}
// Copy input vectors from host memory to GPU buffers.
cudaStatus = cudaMemcpy(dev_a, a, size * sizeof(int), cudaMemcpyHostToDevice);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMemcpy failed!");
goto Error;
}
cudaStatus = cudaMemcpy(dev_b, b, size * sizeof(int), cudaMemcpyHostToDevice);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMemcpy failed!");
goto Error;
}
// Launch a kernel on the GPU with one thread for each element.
addKernel<<<1, size>>>(dev_c, dev_a, dev_b);
// Check for any errors launching the kernel
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "addKernel launch failed: %s\n", cudaGetErrorString(cudaStatus));
goto Error;
}
// cudaDeviceSynchronize waits for the kernel to finish, and returns
// any errors encountered during the launch.
cudaStatus = cudaDeviceSynchronize();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching addKernel!\n", cudaStatus);
goto Error;
}
// Copy output vector from GPU buffer to host memory.
cudaStatus = cudaMemcpy(c, dev_c, size * sizeof(int), cudaMemcpyDeviceToHost);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMemcpy failed!");
goto Error;
}
Error:
cudaFree(dev_c);
cudaFree(dev_a);
cudaFree(dev_b);
return cudaStatus;
}
代碼分析
其實不難發現,CUDA處理的流程如下。
1) 選擇計算的GPU
2) 分配顯存(或內存)空間
3) 初始化數據
4) 調用核函數
5) 處理結果數據
6) 釋放顯存(或內存)空間
SDK 和函數庫
庫名 | 說明 |
---|---|
Thrust | 一個類似於STL針對CUDA的C++模板庫 |
NVPP | 英偉達基本性能庫 |
cuBLAS | GPU 的基本線性代數函數庫 |
CUFFT | GPU 的快速傅里葉函數庫 |
cuSparse | GPU 的稀疏矩陣數據的線性代數和矩陣操作庫 |
Magma | 一個用於數值計算和線性代數計算的函數庫 |
GPU AI | GPU 路徑規劃函數庫 |
CUDA Math lib | GPU 標準數學函數 |
站在巨人的肩膀上,會讓事情事半功倍。讓更多的時間放在算法上,以及生活上。
參考:
《GPGPU編程技術——從GLSL、CUDA到OpenCL》♥♥♥♥♥
《數字圖像處理高級應用——基於MATLAB與CUDA的實現》♥♥♥
《基於CUDA的並行程序設計》♥♥♥
《CUDA專家手冊》♥♥♥♥♥
《高性能CUDA應用設計與開發》♥♥♥♥