CUDA Samples: green ball
生活随笔
收集整理的這篇文章主要介紹了
CUDA Samples: green ball
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
以下CUDA sample是分別用C++和CUDA實(shí)現(xiàn)的生成的綠色的球圖像,并對(duì)其中使用到的CUDA函數(shù)進(jìn)行了解說(shuō),code參考了《GPU高性能編程CUDA實(shí)戰(zhàn)》一書(shū)的第五章,各個(gè)文件內(nèi)容如下:
funset.cpp:
#include "funset.hpp"
#include <random>
#include <iostream>
#include <vector>
#include <memory>
#include <string>
#include "common.hpp"
#include <opencv2/opencv.hpp>int test_green_ball()
{const int width{ 512 }, height = width;cv::Mat mat1(height, width, CV_8UC4), mat2(height, width, CV_8UC4);float elapsed_time1{ 0.f }, elapsed_time2{ 0.f }; // millisecondsint ret = green_ball_cpu(mat1.data, width, height, &elapsed_time1);if (ret != 0) PRINT_ERROR_INFO(green_ball_cpu);ret = green_ball_gpu(mat2.data, width, height, &elapsed_time2);if (ret != 0) PRINT_ERROR_INFO(green_ball_gpu);for (int y = 0; y < height; ++y) {for (int x = 0; x < width; ++x) {cv::Vec4b val1 = mat1.at<cv::Vec4b>(y, x);cv::Vec4b val2 = mat2.at<cv::Vec4b>(y, x);for (int i = 0; i < 4; ++i) {if (val1[i] != val2[i]) {fprintf(stderr, "their values are different at (%d, %d), i: %d, val1: %d, val2: %d\n",x, y, i, val1[i], val2[i]);//return -1;}}}}const std::string save_image_name{ "E:/GitCode/CUDA_Test/gree_ball.jpg" };cv::imwrite(save_image_name, mat2);fprintf(stderr, "test green ball: cpu run time: %f ms, gpu run time: %f ms\n", elapsed_time1, elapsed_time2);return 0;
}
green_ball.cpp:
#include "funset.hpp"
#include <chrono>
#include "common.hpp"int green_ball_cpu(unsigned char* ptr, int width, int height, float* elapsed_time)
{auto start = std::chrono::steady_clock::now();const float period{ 128.0f };for (int y = 0; y < height; ++y) {for (int x = 0; x < width; ++x) {int offset = x + y * width;unsigned char grey = (unsigned char)(255 * (sinf(x * 2.0f * PI / period) + 1.0f) *(sinf(y * 2.0f * PI / period) + 1.0f) / 4.0f) ;ptr[offset * 4 + 0] = 0;ptr[offset * 4 + 1] = grey;ptr[offset * 4 + 2] = 0;ptr[offset * 4 + 3] = 255;}}auto end = std::chrono::steady_clock::now();auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);*elapsed_time = duration.count() * 1.0e-6;return 0;
}
green_ball.cu:
#include "funset.hpp"
#include <iostream>
#include <algorithm>
#include <memory>
#include <cuda_runtime.h> // For the CUDA runtime routines (prefixed with "cuda_")
#include <device_launch_parameters.h>
#include "common.hpp"/* __global__: 函數(shù)類型限定符;在設(shè)備上運(yùn)行;在主機(jī)端調(diào)用,計(jì)算能力3.2及以上可以在
設(shè)備端調(diào)用;聲明的函數(shù)的返回值必須是void類型;對(duì)此類型函數(shù)的調(diào)用是異步的,即在
設(shè)備完全完成它的運(yùn)行之前就返回了;對(duì)此類型函數(shù)的調(diào)用必須指定執(zhí)行配置,即用于在
設(shè)備上執(zhí)行函數(shù)時(shí)的grid和block的維度,以及相關(guān)的流(即插入<<< >>>運(yùn)算符);
a kernel,表示此函數(shù)為內(nèi)核函數(shù)(運(yùn)行在GPU上的CUDA并行計(jì)算函數(shù)稱為kernel(內(nèi)核函
數(shù)),內(nèi)核函數(shù)必須通過(guò)__global__函數(shù)類型限定符定義); */
__global__ static void green_ball(unsigned char* ptr, int width, int height)
{/* gridDim: 內(nèi)置變量,用于描述線程網(wǎng)格的維度,對(duì)于所有線程塊來(lái)說(shuō),這個(gè)變量是一個(gè)常數(shù),用來(lái)保存線程格每一維的大小,即每個(gè)線程格中線程塊的數(shù)量.一個(gè)grid最多只有二維,為dim3類型;blockDim: 內(nèi)置變量,用于說(shuō)明每個(gè)block的維度與尺寸.為dim3類型,包含了block在三個(gè)維度上的尺寸信息;對(duì)于所有線程塊來(lái)說(shuō),這個(gè)變量是一個(gè)常數(shù),保存的是線程塊中每一維的線程數(shù)量;blockIdx: 內(nèi)置變量,變量中包含的值就是當(dāng)前執(zhí)行設(shè)備代碼的線程塊的索引;用于說(shuō)明當(dāng)前thread所在的block在整個(gè)grid中的位置,blockIdx.x取值范圍是[0,gridDim.x-1],blockIdx.y取值范圍是[0, gridDim.y-1].為uint3類型,包含了一個(gè)block在grid中各個(gè)維度上的索引信息;threadIdx: 內(nèi)置變量,變量中包含的值就是當(dāng)前執(zhí)行設(shè)備代碼的線程索引;用于說(shuō)明當(dāng)前thread在block中的位置;如果線程是一維的可獲取threadIdx.x,如果是二維的還可獲取threadIdx.y,如果是三維的還可獲取threadIdx.z;為uint3類型,包含了一個(gè)thread在block中各個(gè)維度的索引信息 */// map from threadIdx/BlockIdx to pixel positionint x = threadIdx.x + blockIdx.x * blockDim.x;int y = threadIdx.y + blockIdx.y * blockDim.y;int offset = x + y * blockDim.x * gridDim.x;/* __shared__: 變量類型限定符;使用__shared__限定符,或者與__device__限定符連用,此時(shí)聲明的變量位于block中的共享存儲(chǔ)器空間中,與block具有相同的生命周期,僅可通過(guò)block內(nèi)的所有線程訪問(wèn);__shared__和__constant__變量默認(rèn)為是靜態(tài)存儲(chǔ);在__shared__前可以加extern關(guān)鍵字,但表示的是變量大小由執(zhí)行參數(shù)確定;__shared__變量在聲明時(shí)不能初始化;可以將CUDA C的關(guān)鍵字__shared__添加到變量聲明中,這將使這個(gè)變量駐留在共享內(nèi)存中;CUDA C編譯器對(duì)共享內(nèi)存中的變量與普通變量將分別采取不同的處理方式 */__shared__ float shared[16][16]; // == threads_block// now calculate the value at that positionconst float period = 128.0f;shared[threadIdx.x][threadIdx.y] = 255 * (sinf(x*2.0f*PI / period) + 1.0f) *(sinf(y*2.0f*PI / period) + 1.0f) / 4.0f;/* __syncthreads: 對(duì)線程塊中的線程進(jìn)行同步;CUDA架構(gòu)將確保,除非線程塊中的每個(gè)線程都執(zhí)行了__syncthreads(),否則沒(méi)有任何線程能執(zhí)行__syncthreads()之后的指令;在同一個(gè)block中的線程通過(guò)共享存儲(chǔ)器(sharedmemory)交換數(shù)據(jù),并通過(guò)柵欄同步(可以在kernel函數(shù)中需要同步的位置調(diào)用__syncthreads()函數(shù))保證線程間能夠正確地共享數(shù)據(jù);使用clock()函數(shù)計(jì)時(shí),在內(nèi)核函數(shù)中要測(cè)量的一段代碼的開(kāi)始和結(jié)束的位置分別調(diào)用一次clock()函數(shù),并將結(jié)果記錄下來(lái)。由于調(diào)用__syncthreads()函數(shù)后,一個(gè)block中的所有thread需要的時(shí)間是相同的,因此只需要記錄每個(gè)block執(zhí)行需要的時(shí)間就行了,而不需要記錄每個(gè)thread的時(shí)間 */// removing this syncthreads shows graphically what happens// when it doesn't exist.this is an example of why we need it.__syncthreads();ptr[offset * 4 + 0] = 0;ptr[offset * 4 + 1] = shared[/*15 - */threadIdx.x][/*15 - */threadIdx.y];ptr[offset * 4 + 2] = 0;ptr[offset * 4 + 3] = 255;
}int green_ball_gpu(unsigned char* ptr, int width, int height, float* elapsed_time)
{/* cudaEvent_t: CUDA event types,結(jié)構(gòu)體類型, CUDA事件,用于測(cè)量GPU在某個(gè)任務(wù)上花費(fèi)的時(shí)間,CUDA中的事件本質(zhì)上是一個(gè)GPU時(shí)間戳,由于CUDA事件是在GPU上實(shí)現(xiàn)的,因此它們不適于對(duì)同時(shí)包含設(shè)備代碼和主機(jī)代碼的混合代碼計(jì)時(shí) */cudaEvent_t start, stop;// cudaEventCreate: 創(chuàng)建一個(gè)事件對(duì)象,異步啟動(dòng)cudaEventCreate(&start);cudaEventCreate(&stop);// cudaEventRecord: 記錄一個(gè)事件,異步啟動(dòng),start記錄起始時(shí)間cudaEventRecord(start, 0);const size_t length{ width * height * 4 * sizeof(unsigned char) };unsigned char* dev{ nullptr };// cudaMalloc: 在設(shè)備端分配內(nèi)存cudaMalloc(&dev, length);const int threads_block{ 16 };dim3 blocks(width / threads_block, height / threads_block);dim3 threads(threads_block, threads_block);/* <<< >>>: 為CUDA引入的運(yùn)算符,指定線程網(wǎng)格和線程塊維度等,傳遞執(zhí)行參數(shù)給CUDA編譯器和運(yùn)行時(shí)系統(tǒng),用于說(shuō)明內(nèi)核函數(shù)中的線程數(shù)量,以及線程是如何組織的;尖括號(hào)中這些參數(shù)并不是傳遞給設(shè)備代碼的參數(shù),而是告訴運(yùn)行時(shí)如何啟動(dòng)設(shè)備代碼,傳遞給設(shè)備代碼本身的參數(shù)是放在圓括號(hào)中傳遞的,就像標(biāo)準(zhǔn)的函數(shù)調(diào)用一樣;不同計(jì)算能力的設(shè)備對(duì)線程的總數(shù)和組織方式有不同的約束;必須先為kernel中用到的數(shù)組或變量分配好足夠的空間,再調(diào)用kernel函數(shù),否則在GPU計(jì)算時(shí)會(huì)發(fā)生錯(cuò)誤,例如越界等;使用運(yùn)行時(shí)API時(shí),需要在調(diào)用的內(nèi)核函數(shù)名與參數(shù)列表直接以<<<Dg,Db,Ns,S>>>的形式設(shè)置執(zhí)行配置,其中:Dg是一個(gè)dim3型變量,用于設(shè)置grid的維度和各個(gè)維度上的尺寸.設(shè)置好Dg后,grid中將有Dg.x*Dg.y個(gè)block,Dg.z必須為1;Db是一個(gè)dim3型變量,用于設(shè)置block的維度和各個(gè)維度上的尺寸.設(shè)置好Db后,每個(gè)block中將有Db.x*Db.y*Db.z個(gè)thread;Ns是一個(gè)size_t型變量,指定各塊為此調(diào)用動(dòng)態(tài)分配的共享存儲(chǔ)器大小,這些動(dòng)態(tài)分配的存儲(chǔ)器可供聲明為外部數(shù)組(extern __shared__)的其他任何變量使用;Ns是一個(gè)可選參數(shù),默認(rèn)值為0;S為cudaStream_t類型,用于設(shè)置與內(nèi)核函數(shù)關(guān)聯(lián)的流.S是一個(gè)可選參數(shù),默認(rèn)值0. */green_ball << <blocks, threads >> >(dev, width, height);/* cudaMemcpy: 在主機(jī)端和設(shè)備端拷貝數(shù)據(jù),此函數(shù)第四個(gè)參數(shù)僅能是下面之一:(1). cudaMemcpyHostToHost: 拷貝數(shù)據(jù)從主機(jī)端到主機(jī)端(2). cudaMemcpyHostToDevice: 拷貝數(shù)據(jù)從主機(jī)端到設(shè)備端(3). cudaMemcpyDeviceToHost: 拷貝數(shù)據(jù)從設(shè)備端到主機(jī)端(4). cudaMemcpyDeviceToDevice: 拷貝數(shù)據(jù)從設(shè)備端到設(shè)備端(5). cudaMemcpyDefault: 從指針值自動(dòng)推斷拷貝數(shù)據(jù)方向,需要支持統(tǒng)一虛擬尋址(CUDA6.0及以上版本)cudaMemcpy函數(shù)對(duì)于主機(jī)是同步的 */cudaMemcpy(ptr, dev, length, cudaMemcpyDeviceToHost);// cudaFree: 釋放設(shè)備上由cudaMalloc函數(shù)分配的內(nèi)存cudaFree(dev);// cudaEventRecord: 記錄一個(gè)事件,異步啟動(dòng),stop記錄結(jié)束時(shí)間cudaEventRecord(stop, 0);// cudaEventSynchronize: 事件同步,等待一個(gè)事件完成,異步啟動(dòng)cudaEventSynchronize(stop);// cudaEventElapseTime: 計(jì)算兩個(gè)事件之間經(jīng)歷的時(shí)間,單位為毫秒,異步啟動(dòng)cudaEventElapsedTime(elapsed_time, start, stop);// cudaEventDestroy: 銷(xiāo)毀事件對(duì)象,異步啟動(dòng)cudaEventDestroy(start);cudaEventDestroy(stop);return 0;
}
生成的結(jié)果圖像如下:
執(zhí)行結(jié)果如下:可見(jiàn)使用C++和CUDA實(shí)現(xiàn)的結(jié)果是完全一致的。 GitHub:?https://github.com/fengbingchun/CUDA_Test
總結(jié)
以上是生活随笔為你收集整理的CUDA Samples: green ball的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: CUDA Samples: ripple
- 下一篇: CUDA Samples: Ray Tr