CUDA Samples: heat conduction(模拟热传导)
生活随笔
收集整理的這篇文章主要介紹了
CUDA Samples: heat conduction(模拟热传导)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
以下CUDA sample是分別用C++和CUDA實現(xiàn)的模擬熱傳導生成的圖像,并對其中使用到的CUDA函數(shù)進行了解說,code參考了《GPU高性能編程CUDA實戰(zhàn)》一書的第七章,各個文件內容如下:
funset.cpp:
#include "funset.hpp"
#include <random>
#include <iostream>
#include <vector>
#include <memory>
#include <string>
#include "common.hpp"
#include <opencv2/opencv.hpp>int test_heat_conduction()
{const int width{ 1024 }, height = width;cv::Mat mat1(height, width, CV_8UC4), mat2(height, width, CV_8UC4);const float speed{ 0.25f }, max_temp{ 1.f }, min_temp{0.0001f};float elapsed_time1{ 0.f }, elapsed_time2{ 0.f }; // milliseconds// intialize the constant datastd::unique_ptr<float[]> temp(new float[width * height]);for (int i = 0; i < width*height; ++i) {temp[i] = 0;int x = i % width;int y = i / height;if ((x>300) && (x<600) && (y>310) && (y<601))temp[i] = max_temp;}temp[width * 100 + 100] = (max_temp + min_temp) / 2;temp[width * 700 + 100] = min_temp;temp[width * 300 + 300] = min_temp;temp[width * 200 + 700] = min_temp;for (int y = 800; y < 900; ++y) {for (int x = 400; x < 500; ++x) {temp[x + y * width] = min_temp;}}int ret = heat_conduction_cpu(mat1.data, width, height, temp.get(), speed, &elapsed_time1);if (ret != 0) PRINT_ERROR_INFO(heat_conduction_cpu);ret = heat_conduction_gpu(mat2.data, width, height, temp.get(), speed, &elapsed_time2);if (ret != 0) PRINT_ERROR_INFO(heat_conduction_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;}}}}std::string save_image_name{ "E:/GitCode/CUDA_Test/heat_conduction.jpg" };cv::resize(mat2, mat2, cv::Size(width / 2, height / 2), 0.f, 0.f, 2);cv::imwrite(save_image_name, mat2);fprintf(stderr, "test heat conduction: cpu run time: %f ms, gpu run time: %f ms\n", elapsed_time1, elapsed_time2);return 0;
}
heat_conduction.cpp:
#include "funset.hpp"
#include <chrono>
#include <memory>
#include <vector>static void copy_const_kernel(float* iptr, const float* cptr, int width, int height)
{for (int y = 0; y < height; ++y) {for (int x = 0; x < width; ++x) {int offset = x + y * width;if (cptr[offset] != 0) iptr[offset] = cptr[offset];}}
}static void blend_kernel(float* outSrc, const float* inSrc, int width, int height, float speed)
{for (int y = 0; y < height; ++y) {for (int x = 0; x < width; ++x) {int offset = x + y * width;int left = offset - 1;int right = offset + 1;if (x == 0) ++left;if (x == width - 1) --right;int top = offset - height;int bottom = offset + height;if (y == 0) top += height;if (y == height - 1) bottom -= height;outSrc[offset] = inSrc[offset] + speed * (inSrc[top] + inSrc[bottom] + inSrc[left] + inSrc[right] - inSrc[offset] * 4);}}
}static unsigned char value(float n1, float n2, int hue)
{if (hue > 360) hue -= 360;else if (hue < 0) hue += 360;if (hue < 60)return (unsigned char)(255 * (n1 + (n2 - n1)*hue / 60));if (hue < 180)return (unsigned char)(255 * n2);if (hue < 240)return (unsigned char)(255 * (n1 + (n2 - n1)*(240 - hue) / 60));return (unsigned char)(255 * n1);
}static void float_to_color(unsigned char *optr, const float *outSrc, int width, int height)
{for (int y = 0; y < height; ++y) {for (int x = 0; x < width; ++x) {int offset = x + y * width;float l = outSrc[offset];float s = 1;int h = (180 + (int)(360.0f * outSrc[offset])) % 360;float m1, m2;if (l <= 0.5f) m2 = l * (1 + s);else m2 = l + s - l * s;m1 = 2 * l - m2;optr[offset * 4 + 0] = value(m1, m2, h + 120);optr[offset * 4 + 1] = value(m1, m2, h);optr[offset * 4 + 2] = value(m1, m2, h - 120);optr[offset * 4 + 3] = 255;}}
}int heat_conduction_cpu(unsigned char* ptr, int width, int height, const float* src, float speed, float* elapsed_time)
{auto start = std::chrono::steady_clock::now();std::vector<float> inSrc(width*height, 0.f);std::vector<float> outSrc(width*height, 0.f);for (int i = 0; i < 90; ++i) {copy_const_kernel(inSrc.data(), src, width, height);blend_kernel(outSrc.data(), inSrc.data(), width, height, speed);std::swap(inSrc, outSrc);}float_to_color(ptr, inSrc.data(), width, height);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;
}
heat_conduction.cu:
#include "funset.hpp"
#include <iostream>
#include <algorithm>
#include <memory>
#include <vector>
#include <cuda_runtime.h> // For the CUDA runtime routines (prefixed with "cuda_")
#include <device_launch_parameters.h>
#include "common.hpp"/* __global__: 函數(shù)類型限定符;在設備上運行;在主機端調用,計算能力3.2及以上可以在
設備端調用;聲明的函數(shù)的返回值必須是void類型;對此類型函數(shù)的調用是異步的,即在
設備完全完成它的運行之前就返回了;對此類型函數(shù)的調用必須指定執(zhí)行配置,即用于在
設備上執(zhí)行函數(shù)時的grid和block的維度,以及相關的流(即插入<<< >>>運算符);
a kernel,表示此函數(shù)為內核函數(shù)(運行在GPU上的CUDA并行計算函數(shù)稱為kernel(內核函
數(shù)),內核函數(shù)必須通過__global__函數(shù)類型限定符定義); */
__global__ static void copy_const_kernel(float* iptr, const float* cptr)
{/* gridDim: 內置變量,用于描述線程網(wǎng)格的維度,對于所有線程塊來說,這個變量是一個常數(shù),用來保存線程格每一維的大小,即每個線程格中線程塊的數(shù)量.一個grid最多只有二維,為dim3類型;blockDim: 內置變量,用于說明每個block的維度與尺寸.為dim3類型,包含了block在三個維度上的尺寸信息;對于所有線程塊來說,這個變量是一個常數(shù),保存的是線程塊中每一維的線程數(shù)量;blockIdx: 內置變量,變量中包含的值就是當前執(zhí)行設備代碼的線程塊的索引;用于說明當前thread所在的block在整個grid中的位置,blockIdx.x取值范圍是[0,gridDim.x-1],blockIdx.y取值范圍是[0, gridDim.y-1].為uint3類型,包含了一個block在grid中各個維度上的索引信息;threadIdx: 內置變量,變量中包含的值就是當前執(zhí)行設備代碼的線程索引;用于說明當前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;if (cptr[offset] != 0) iptr[offset] = cptr[offset];
}__global__ static void blend_kernel(float* outSrc, const float* inSrc, int width, int height, float speed)
{// 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;int left = offset - 1;int right = offset + 1;if (x == 0) ++left;if (x == width - 1) --right;int top = offset - height;int bottom = offset + height;if (y == 0) top += height;if (y == height - 1) bottom -= height;outSrc[offset] = inSrc[offset] + speed * (inSrc[top] + inSrc[bottom] + inSrc[left] + inSrc[right] - inSrc[offset] * 4);
}/* __device__: 函數(shù)類型限定符,表明被修飾的函數(shù)在設備上執(zhí)行,只能從設備上調用,
但只能在其它__device__函數(shù)或者__global__函數(shù)中調用;__device__函數(shù)不支持遞歸;
__device__函數(shù)的函數(shù)體內不能聲明靜態(tài)變量;__device__函數(shù)的參數(shù)數(shù)目是不可變化的;
不能對__device__函數(shù)取指針 */
__device__ static unsigned char value(float n1, float n2, int hue)
{if (hue > 360) hue -= 360;else if (hue < 0) hue += 360;if (hue < 60)return (unsigned char)(255 * (n1 + (n2 - n1)*hue / 60));if (hue < 180)return (unsigned char)(255 * n2);if (hue < 240)return (unsigned char)(255 * (n1 + (n2 - n1)*(240 - hue) / 60));return (unsigned char)(255 * n1);
}__global__ static void float_to_color(unsigned char *optr, const float *outSrc)
{// 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;float l = outSrc[offset];float s = 1;int h = (180 + (int)(360.0f * outSrc[offset])) % 360;float m1, m2;if (l <= 0.5f) m2 = l * (1 + s);else m2 = l + s - l * s;m1 = 2 * l - m2;optr[offset * 4 + 0] = value(m1, m2, h + 120);optr[offset * 4 + 1] = value(m1, m2, h);optr[offset * 4 + 2] = value(m1, m2, h - 120);optr[offset * 4 + 3] = 255;
}static int heat_conduction_gpu_1(unsigned char* ptr, int width, int height, const float* src, float speed, float* elapsed_time)
{/* cudaEvent_t: CUDA event types,結構體類型, CUDA事件,用于測量GPU在某個任務上花費的時間,CUDA中的事件本質上是一個GPU時間戳,由于CUDA事件是在GPU上實現(xiàn)的,因此它們不適于對同時包含設備代碼和主機代碼的混合代碼計時 */cudaEvent_t start, stop;// cudaEventCreate: 創(chuàng)建一個事件對象,異步啟動cudaEventCreate(&start);cudaEventCreate(&stop);// cudaEventRecord: 記錄一個事件,異步啟動,start記錄起始時間cudaEventRecord(start, 0);float* dev_inSrc{ nullptr };float* dev_outSrc{ nullptr };float* dev_constSrc{ nullptr };unsigned char* dev_image{ nullptr };const size_t length1{ width * height * sizeof(float) };const size_t length2{ width * height * 4 * sizeof(unsigned char) };// cudaMalloc: 在設備端分配內存cudaMalloc(&dev_inSrc, length1);cudaMalloc(&dev_outSrc, length1);cudaMalloc(&dev_constSrc, length1);cudaMalloc(&dev_image, length2);/* cudaMemcpy: 在主機端和設備端拷貝數(shù)據(jù),此函數(shù)第四個參數(shù)僅能是下面之一:(1). cudaMemcpyHostToHost: 拷貝數(shù)據(jù)從主機端到主機端(2). cudaMemcpyHostToDevice: 拷貝數(shù)據(jù)從主機端到設備端(3). cudaMemcpyDeviceToHost: 拷貝數(shù)據(jù)從設備端到主機端(4). cudaMemcpyDeviceToDevice: 拷貝數(shù)據(jù)從設備端到設備端(5). cudaMemcpyDefault: 從指針值自動推斷拷貝數(shù)據(jù)方向,需要支持統(tǒng)一虛擬尋址(CUDA6.0及以上版本)cudaMemcpy函數(shù)對于主機是同步的 */cudaMemcpy(dev_constSrc, src, length1, cudaMemcpyHostToDevice);const int threads_block{ 16 };/* dim3: 基于uint3定義的內置矢量類型,相當于由3個unsigned int類型組成的結構體,可表示一個三維數(shù)組,在定義dim3類型變量時,凡是沒有賦值的元素都會被賦予默認值1 */dim3 blocks(width / threads_block, height / threads_block);dim3 threads(threads_block, threads_block);for (int i = 0; i < 90; ++i) {copy_const_kernel << <blocks, threads >> >(dev_inSrc, dev_constSrc);blend_kernel << <blocks, threads >> >(dev_outSrc, dev_inSrc, width, height, speed);std::swap(dev_inSrc, dev_outSrc);}/* <<< >>>: 為CUDA引入的運算符,指定線程網(wǎng)格和線程塊維度等,傳遞執(zhí)行參數(shù)給CUDA編譯器和運行時系統(tǒng),用于說明內核函數(shù)中的線程數(shù)量,以及線程是如何組織的;尖括號中這些參數(shù)并不是傳遞給設備代碼的參數(shù),而是告訴運行時如何啟動設備代碼,傳遞給設備代碼本身的參數(shù)是放在圓括號中傳遞的,就像標準的函數(shù)調用一樣;不同計算能力的設備對線程的總數(shù)和組織方式有不同的約束;必須先為kernel中用到的數(shù)組或變量分配好足夠的空間,再調用kernel函數(shù),否則在GPU計算時會發(fā)生錯誤,例如越界等;使用運行時API時,需要在調用的內核函數(shù)名與參數(shù)列表直接以<<<Dg,Db,Ns,S>>>的形式設置執(zhí)行配置,其中:Dg是一個dim3型變量,用于設置grid的維度和各個維度上的尺寸.設置好Dg后,grid中將有Dg.x*Dg.y個block,Dg.z必須為1;Db是一個dim3型變量,用于設置block的維度和各個維度上的尺寸.設置好Db后,每個block中將有Db.x*Db.y*Db.z個thread;Ns是一個size_t型變量,指定各塊為此調用動態(tài)分配的共享存儲器大小,這些動態(tài)分配的存儲器可供聲明為外部數(shù)組(extern __shared__)的其他任何變量使用;Ns是一個可選參數(shù),默認值為0;S為cudaStream_t類型,用于設置與內核函數(shù)關聯(lián)的流.S是一個可選參數(shù),默認值0. */float_to_color << <blocks, threads >> >(dev_image, dev_inSrc);cudaMemcpy(ptr, dev_image, length2, cudaMemcpyDeviceToHost);// cudaFree: 釋放設備上由cudaMalloc函數(shù)分配的內存cudaFree(dev_inSrc);cudaFree(dev_outSrc);cudaFree(dev_constSrc);cudaFree(dev_image);// cudaEventRecord: 記錄一個事件,異步啟動,stop記錄結束時間cudaEventRecord(stop, 0);// cudaEventSynchronize: 事件同步,等待一個事件完成,異步啟動cudaEventSynchronize(stop);// cudaEventElapseTime: 計算兩個事件之間經(jīng)歷的時間,單位為毫秒,異步啟動cudaEventElapsedTime(elapsed_time, start, stop);// cudaEventDestroy: 銷毀事件對象,異步啟動cudaEventDestroy(start);cudaEventDestroy(stop);return 0;
}static int heat_conduction_gpu_2(unsigned char* ptr, int width, int height, const float* src, float speed, float* elapsed_time)
{return 0;
}static int heat_conduction_gpu_3(unsigned char* ptr, int width, int height, const float* src, float speed, float* elapsed_time)
{return 0;
}int heat_conduction_gpu(unsigned char* ptr, int width, int height, const float* src, float speed, float* elapsed_time)
{int ret{ 0 };ret = heat_conduction_gpu_1(ptr, width, height, src, speed, elapsed_time); // 沒有采用紋理內存//ret = heat_conduction_gpu_2(ptr, width, height, src, speed, elapsed_time); // 采用一維紋理內存//ret = heat_conduction_gpu_3(ptr, width, height, src, speed, elapsed_time); // 采用二維紋理內存return ret;
}
生成的結果圖像如下:
執(zhí)行結果如下:可見使用C++和CUDA實現(xiàn)的結果是完全一致的:
GitHub:?https://github.com/fengbingchun/CUDA_Test
總結
以上是生活随笔為你收集整理的CUDA Samples: heat conduction(模拟热传导)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CUDA Samples: Ray Tr
- 下一篇: CUDA Samples: Calcul