CUDA Samples: green ball
生活随笔
收集整理的這篇文章主要介紹了
CUDA Samples: green ball
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
以下CUDA sample是分別用C++和CUDA實現(xiàn)的生成的綠色的球圖像,并對其中使用到的CUDA函數(shù)進行了解說,code參考了《GPU高性能編程CUDA實戰(zhàn)》一書的第五章,各個文件內(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è)備上運行;在主機端調(diào)用,計算能力3.2及以上可以在
設(shè)備端調(diào)用;聲明的函數(shù)的返回值必須是void類型;對此類型函數(shù)的調(diào)用是異步的,即在
設(shè)備完全完成它的運行之前就返回了;對此類型函數(shù)的調(diào)用必須指定執(zhí)行配置,即用于在
設(shè)備上執(zhí)行函數(shù)時的grid和block的維度,以及相關(guān)的流(即插入<<< >>>運算符);
a kernel,表示此函數(shù)為內(nèi)核函數(shù)(運行在GPU上的CUDA并行計算函數(shù)稱為kernel(內(nèi)核函
數(shù)),內(nèi)核函數(shù)必須通過__global__函數(shù)類型限定符定義); */
__global__ static void green_ball(unsigned char* ptr, int width, int height)
{/* gridDim: 內(nèi)置變量,用于描述線程網(wǎng)格的維度,對于所有線程塊來說,這個變量是一個常數(shù),用來保存線程格每一維的大小,即每個線程格中線程塊的數(shù)量.一個grid最多只有二維,為dim3類型;blockDim: 內(nèi)置變量,用于說明每個block的維度與尺寸.為dim3類型,包含了block在三個維度上的尺寸信息;對于所有線程塊來說,這個變量是一個常數(shù),保存的是線程塊中每一維的線程數(shù)量;blockIdx: 內(nèi)置變量,變量中包含的值就是當前執(zhí)行設(shè)備代碼的線程塊的索引;用于說明當前thread所在的block在整個grid中的位置,blockIdx.x取值范圍是[0,gridDim.x-1],blockIdx.y取值范圍是[0, gridDim.y-1].為uint3類型,包含了一個block在grid中各個維度上的索引信息;threadIdx: 內(nèi)置變量,變量中包含的值就是當前執(zhí)行設(shè)備代碼的線程索引;用于說明當前thread在block中的位置;如果線程是一維的可獲取threadIdx.x,如果是二維的還可獲取threadIdx.y,如果是三維的還可獲取threadIdx.z;為uint3類型,包含了一個thread在block中各個維度的索引信息 */// 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__限定符連用,此時聲明的變量位于block中的共享存儲器空間中,與block具有相同的生命周期,僅可通過block內(nèi)的所有線程訪問;__shared__和__constant__變量默認為是靜態(tài)存儲;在__shared__前可以加extern關(guān)鍵字,但表示的是變量大小由執(zhí)行參數(shù)確定;__shared__變量在聲明時不能初始化;可以將CUDA C的關(guān)鍵字__shared__添加到變量聲明中,這將使這個變量駐留在共享內(nèi)存中;CUDA C編譯器對共享內(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: 對線程塊中的線程進行同步;CUDA架構(gòu)將確保,除非線程塊中的每個線程都執(zhí)行了__syncthreads(),否則沒有任何線程能執(zhí)行__syncthreads()之后的指令;在同一個block中的線程通過共享存儲器(sharedmemory)交換數(shù)據(jù),并通過柵欄同步(可以在kernel函數(shù)中需要同步的位置調(diào)用__syncthreads()函數(shù))保證線程間能夠正確地共享數(shù)據(jù);使用clock()函數(shù)計時,在內(nèi)核函數(shù)中要測量的一段代碼的開始和結(jié)束的位置分別調(diào)用一次clock()函數(shù),并將結(jié)果記錄下來。由于調(diào)用__syncthreads()函數(shù)后,一個block中的所有thread需要的時間是相同的,因此只需要記錄每個block執(zhí)行需要的時間就行了,而不需要記錄每個thread的時間 */// 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事件,用于測量GPU在某個任務(wù)上花費的時間,CUDA中的事件本質(zhì)上是一個GPU時間戳,由于CUDA事件是在GPU上實現(xiàn)的,因此它們不適于對同時包含設(shè)備代碼和主機代碼的混合代碼計時 */cudaEvent_t start, stop;// cudaEventCreate: 創(chuàng)建一個事件對象,異步啟動cudaEventCreate(&start);cudaEventCreate(&stop);// cudaEventRecord: 記錄一個事件,異步啟動,start記錄起始時間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引入的運算符,指定線程網(wǎng)格和線程塊維度等,傳遞執(zhí)行參數(shù)給CUDA編譯器和運行時系統(tǒng),用于說明內(nèi)核函數(shù)中的線程數(shù)量,以及線程是如何組織的;尖括號中這些參數(shù)并不是傳遞給設(shè)備代碼的參數(shù),而是告訴運行時如何啟動設(shè)備代碼,傳遞給設(shè)備代碼本身的參數(shù)是放在圓括號中傳遞的,就像標準的函數(shù)調(diào)用一樣;不同計算能力的設(shè)備對線程的總數(shù)和組織方式有不同的約束;必須先為kernel中用到的數(shù)組或變量分配好足夠的空間,再調(diào)用kernel函數(shù),否則在GPU計算時會發(fā)生錯誤,例如越界等;使用運行時API時,需要在調(diào)用的內(nèi)核函數(shù)名與參數(shù)列表直接以<<<Dg,Db,Ns,S>>>的形式設(shè)置執(zhí)行配置,其中:Dg是一個dim3型變量,用于設(shè)置grid的維度和各個維度上的尺寸.設(shè)置好Dg后,grid中將有Dg.x*Dg.y個block,Dg.z必須為1;Db是一個dim3型變量,用于設(shè)置block的維度和各個維度上的尺寸.設(shè)置好Db后,每個block中將有Db.x*Db.y*Db.z個thread;Ns是一個size_t型變量,指定各塊為此調(diào)用動態(tài)分配的共享存儲器大小,這些動態(tài)分配的存儲器可供聲明為外部數(shù)組(extern __shared__)的其他任何變量使用;Ns是一個可選參數(shù),默認值為0;S為cudaStream_t類型,用于設(shè)置與內(nèi)核函數(shù)關(guān)聯(lián)的流.S是一個可選參數(shù),默認值0. */green_ball << <blocks, threads >> >(dev, width, height);/* cudaMemcpy: 在主機端和設(shè)備端拷貝數(shù)據(jù),此函數(shù)第四個參數(shù)僅能是下面之一:(1). cudaMemcpyHostToHost: 拷貝數(shù)據(jù)從主機端到主機端(2). cudaMemcpyHostToDevice: 拷貝數(shù)據(jù)從主機端到設(shè)備端(3). cudaMemcpyDeviceToHost: 拷貝數(shù)據(jù)從設(shè)備端到主機端(4). cudaMemcpyDeviceToDevice: 拷貝數(shù)據(jù)從設(shè)備端到設(shè)備端(5). cudaMemcpyDefault: 從指針值自動推斷拷貝數(shù)據(jù)方向,需要支持統(tǒng)一虛擬尋址(CUDA6.0及以上版本)cudaMemcpy函數(shù)對于主機是同步的 */cudaMemcpy(ptr, dev, length, cudaMemcpyDeviceToHost);// cudaFree: 釋放設(shè)備上由cudaMalloc函數(shù)分配的內(nèi)存cudaFree(dev);// cudaEventRecord: 記錄一個事件,異步啟動,stop記錄結(jié)束時間cudaEventRecord(stop, 0);// cudaEventSynchronize: 事件同步,等待一個事件完成,異步啟動cudaEventSynchronize(stop);// cudaEventElapseTime: 計算兩個事件之間經(jīng)歷的時間,單位為毫秒,異步啟動cudaEventElapsedTime(elapsed_time, start, stop);// cudaEventDestroy: 銷毀事件對象,異步啟動cudaEventDestroy(start);cudaEventDestroy(stop);return 0;
}
生成的結(jié)果圖像如下:
執(zhí)行結(jié)果如下:可見使用C++和CUDA實現(xiàn)的結(jié)果是完全一致的。 GitHub:?https://github.com/fengbingchun/CUDA_Test
總結(jié)
以上是生活随笔為你收集整理的CUDA Samples: green ball的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CUDA Samples: ripple
- 下一篇: CUDA Samples: Ray Tr