cuda笔记-第一个cuda程序
生活随笔
收集整理的這篇文章主要介紹了
cuda笔记-第一个cuda程序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這里先說明下一些基本概念:
釋放GPU中的內存cudaFree()
?
CUDA函數的定義:
__global__:定義在GPU上,可以在CPU上調用的函數;
__device__:定義在GPU上,由GPU調用函數;
__host__:在CPU上定義的函數,一般與__device__一起用
?
在GPU上開辟空間:cudaMalloc(**devPtr, byte_size)
如:
int *gpu_int; cudaMalloc((void**)&gpu_int, sizeof(int))GPU上數組的初始化cudaMemset(*devptr, value, byte_size)
GPU、CPU參數傳遞cudaMemcpy(*dst, *src, byte_size, 類型)
其中這個類型包括:
CPU2CPU:cudaMemcpyHostToHost
CPU2GPU:cudaMemcpyHostToDevice
GPU2CPU:cudaMemcpyDeviceToHost
GPU2GPU:cudaMemcpyDeviceToDevice
?
源碼如下:
#include "cuda_runtime.h" #include "device_launch_parameters.h" #include <stdio.h>using namespace std;__device__ int add_one(int a) {return a + 1; }__global__ void show(int *a) {for (int i = 0; i < 10; i++) {//a[i] = add_one(a[i]);printf(" %d", a[i]);}printf("\n"); }__global__ void changeValue(int *a) {for (int i = 0; i < 10; i++) {a[i] = 100;} }int main() {int cpu_int[10] = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10};int *gpu_int;//在GPU上分配空間cudaMalloc((void**)&gpu_int, 10 * sizeof(int));show << <1, 1 >> > (gpu_int);//初始化其值cudaMemset(gpu_int, 0, 10 * sizeof(int));show<< <1, 1 >> > (gpu_int);//將cpu_int賦值給gpu_intcudaMemcpy(gpu_int, cpu_int, 10 * sizeof(int), cudaMemcpyHostToDevice);show << <1, 1 >> > (gpu_int);//改變gpu_int的值changeValue << <1, 1 >> >(gpu_int);show << <1, 1 >> > (gpu_int);//將gpu_int的值賦值到cpu_intcudaMemcpy(cpu_int, gpu_int, 10 * sizeof(int), cudaMemcpyDeviceToHost);printf("----------華麗的分割線----------\n");for (int i = 0; i < 10; i++) {printf(" %d", cpu_int[i]);}//釋放gpu_int的空間cudaFree(gpu_int);getchar();return 0; }程序運行截圖如下:
源碼打包地址如下:
https://github.com/fengfanchen/CAndCPP/tree/master/HelloCuda
總結
以上是生活随笔為你收集整理的cuda笔记-第一个cuda程序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python笔记-使用SSIM找两张图不
- 下一篇: TCP/IP笔记-Qt使用Win10pc