以下CUDA sample是分别用C++和CUDA实现的生成光线跟踪图像,并对其中使用到的CUDA函数进行了解说,code参考了《GPU高性能编程CUDA实战》一书的第六章,CUDA各实现包括了使用常量内存和不使用常量内存两种方法,各个文件内容如下:

funset.cpp:

#include "funset.hpp"
#include <random>
#include <iostream>
#include <vector>
#include <memory>
#include <string>
#include "common.hpp"
#include <opencv2/opencv.hpp>int test_ray_tracking()
{const int spheres{ 20 };std::unique_ptr<float[]> A(new float[spheres * 3]);std::unique_ptr<float[]> B(new float[spheres * 3]);std::unique_ptr<float[]> C(new float[spheres]);generator_random_number(A.get(), spheres * 3, 0.f, 1.f);generator_random_number(B.get(), spheres * 3, -400.f, 400.f);generator_random_number(C.get(), spheres, 20.f, 120.f);float elapsed_time1{ 0.f }, elapsed_time2{ 0.f }; // millisecondsconst int width{ 512 }, height = width;cv::Mat mat1(height, width, CV_8UC4), mat2(height, width, CV_8UC4);int ret = ray_tracking_cpu(A.get(), B.get(), C.get(), spheres, mat1.data, width, height, &elapsed_time1);if (ret != 0) PRINT_ERROR_INFO(ray_tracking_cpu);ret = ray_tracking_gpu(A.get(), B.get(), C.get(), spheres, mat2.data, width, height, &elapsed_time2);if (ret != 0) PRINT_ERROR_INFO(ray_tracking_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/ray_tracking.jpg" };cv::imwrite(save_image_name, mat2);fprintf(stderr, "ray tracking: cpu run time: %f ms, gpu run time: %f ms\n", elapsed_time1, elapsed_time2);return 0;
}

ray_tracking.cpp:

#include "funset.hpp"
#include <chrono>
#include <memory>
#include "common.hpp"// 通过一个数据结构对球面建模
struct Sphere {float r, b, g;float radius;float x, y, z;float hit(float ox, float oy, float *n){float dx = ox - x;float dy = oy - y;if (dx*dx + dy*dy < radius*radius) {float dz = sqrtf(radius*radius - dx*dx - dy*dy);*n = dz / sqrtf(radius * radius);return dz + z;}return -INF;}
};int ray_tracking_cpu(const float* a, const float* b, const float* c, int sphere_num, unsigned char* ptr, int width, int height, float* elapsed_time)
{auto start = std::chrono::steady_clock::now();std::unique_ptr<Sphere[]> spheres(new Sphere[sphere_num]);for (int i = 0, t = 0; i < sphere_num; ++i, t+=3) {spheres[i].r = a[t];spheres[i].g = a[t+1];spheres[i].b = a[t+2];spheres[i].x = b[t];spheres[i].y = b[t+1];spheres[i].z = b[t+2];spheres[i].radius = c[i];}for (int y = 0; y < height; ++y) {for (int x = 0; x < width; ++x) {int offset = x + y * width;float ox{ (x - width / 2.f) };float oy{ (y - height / 2.f) };float r{ 0 }, g{ 0 }, b{ 0 };float maxz{ -INF };for (int i = 0; i < sphere_num; ++i) {float n;float t = spheres[i].hit(ox, oy, &n);if (t > maxz) {float fscale = n;r = spheres[i].r * fscale;g = spheres[i].g * fscale;b = spheres[i].b * fscale;maxz = t;}}ptr[offset * 4 + 0] = static_cast<unsigned char>(r * 255);ptr[offset * 4 + 1] = static_cast<unsigned char>(g * 255);ptr[offset * 4 + 2] = static_cast<unsigned char>(b * 255);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;
}

ray_tracking.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"// 通过一个数据结构对球面建模
struct Sphere {float r, b, g;float radius;float x, y, z;/* __device__: 函数类型限定符,表明被修饰的函数在设备上执行,只能从设备上调用,但只能在其它__device__函数或者__global__函数中调用;__device__函数不支持递归;__device__函数的函数体内不能声明静态变量;__device__函数的参数数目是不可变化的;不能对__device__函数取指针 */__device__ float hit(float ox, float oy, float *n){float dx = ox - x;float dy = oy - y;if (dx*dx + dy*dy < radius*radius) {float dz = sqrtf(radius*radius - dx*dx - dy*dy);*n = dz / sqrtf(radius * radius);return dz + z;}return -INF;}
};// method2: 使用常量内存
/* __constant__: 变量类型限定符,或者与__device__限定符连用,这样声明的变量:存
在于常数存储器空间;与应用程序具有相同的生命周期;可以通过运行时库从主机端访问,
设备端的所有线程也可访问。__constant__变量默认为是静态存储。__constant__不能用
extern关键字声明为外部变量。__constant__变量只能在文件作用域中声明,不能再函数
体内声明。__constant__变量不能从device中赋值,只能从host中通过host运行时函数赋
值。__constant__将把变量的访问限制为只读。与从全局内存中读取数据相比,从常量内
存中读取相同的数据可以节约内存带宽。常量内存用于保存在核函数执行期间不会发生变
化的数据。
常量内存:用于保存在核函数执行期间不会发生变化的数据。NVIDIA硬件提供了64KB的常
量内存,并且对常量内存采取了不同于标准全局内存的处理方式。在某些情况中,用常量
内存来替换全局内存能有效地减少内存带宽。 在某些情况下,使用常量内存将提升应用程
序的性能 */
__constant__ Sphere dev_spheres[20]; // 常量内存, = sphere_num/* __global__: 函数类型限定符;在设备上运行;在主机端调用,计算能力3.2及以上可以在
设备端调用;声明的函数的返回值必须是void类型;对此类型函数的调用是异步的,即在
设备完全完成它的运行之前就返回了;对此类型函数的调用必须指定执行配置,即用于在
设备上执行函数时的grid和block的维度,以及相关的流(即插入<<<   >>>运算符);
a kernel,表示此函数为内核函数(运行在GPU上的CUDA并行计算函数称为kernel(内核函
数),内核函数必须通过__global__函数类型限定符定义); */
__global__ static void ray_tracking(unsigned char* ptr_image, Sphere* ptr_sphere, int width, int height, int sphere_num)
{/* gridDim: 内置变量,用于描述线程网格的维度,对于所有线程块来说,这个变量是一个常数,用来保存线程格每一维的大小,即每个线程格中线程块的数量.一个grid最多只有二维,为dim3类型;blockDim: 内置变量,用于说明每个block的维度与尺寸.为dim3类型,包含了block在三个维度上的尺寸信息;对于所有线程块来说,这个变量是一个常数,保存的是线程块中每一维的线程数量;blockIdx: 内置变量,变量中包含的值就是当前执行设备代码的线程块的索引;用于说明当前thread所在的block在整个grid中的位置,blockIdx.x取值范围是[0,gridDim.x-1],blockIdx.y取值范围是[0, gridDim.y-1].为uint3类型,包含了一个block在grid中各个维度上的索引信息;threadIdx: 内置变量,变量中包含的值就是当前执行设备代码的线程索引;用于说明当前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;float ox{ (x - width / 2.f) };float oy{ (y - height / 2.f) };float r{ 0 }, g{ 0 }, b{ 0 };float maxz{ -INF };for (int i = 0; i < sphere_num; ++i) {float n;float t = ptr_sphere[i].hit(ox, oy, &n);if (t > maxz) {float fscale = n;r = ptr_sphere[i].r * fscale;g = ptr_sphere[i].g * fscale;b = ptr_sphere[i].b * fscale;maxz = t;}}ptr_image[offset * 4 + 0] = static_cast<unsigned char>(r * 255);ptr_image[offset * 4 + 1] = static_cast<unsigned char>(g * 255);ptr_image[offset * 4 + 2] = static_cast<unsigned char>(b * 255);ptr_image[offset * 4 + 3] = 255;
}__global__ static void ray_tracking(unsigned char* ptr_image, int width, int height, int sphere_num)
{int x = threadIdx.x + blockIdx.x * blockDim.x;int y = threadIdx.y + blockIdx.y * blockDim.y;int offset = x + y * blockDim.x * gridDim.x;float ox{ (x - width / 2.f) };float oy{ (y - height / 2.f) };float r{ 0 }, g{ 0 }, b{ 0 };float maxz{ -INF };for (int i = 0; i < sphere_num; ++i) {float n;float t = dev_spheres[i].hit(ox, oy, &n);if (t > maxz) {float fscale = n;r = dev_spheres[i].r * fscale;g = dev_spheres[i].g * fscale;b = dev_spheres[i].b * fscale;maxz = t;}}ptr_image[offset * 4 + 0] = static_cast<unsigned char>(r * 255);ptr_image[offset * 4 + 1] = static_cast<unsigned char>(g * 255);ptr_image[offset * 4 + 2] = static_cast<unsigned char>(b * 255);ptr_image[offset * 4 + 3] = 255;
}int ray_tracking_gpu(const float* a, const float* b, const float* c, int sphere_num, unsigned char* ptr, int width, int height, float* elapsed_time)
{/* cudaEvent_t: CUDA event types,结构体类型, CUDA事件,用于测量GPU在某个任务上花费的时间,CUDA中的事件本质上是一个GPU时间戳,由于CUDA事件是在GPU上实现的,因此它们不适于对同时包含设备代码和主机代码的混合代码计时 */cudaEvent_t start, stop;// cudaEventCreate: 创建一个事件对象,异步启动cudaEventCreate(&start);cudaEventCreate(&stop);// cudaEventRecord: 记录一个事件,异步启动,start记录起始时间cudaEventRecord(start, 0);const size_t length{ width * height * 4 * sizeof(unsigned char) };unsigned char* dev_image{ nullptr };std::unique_ptr<Sphere[]> spheres(new Sphere[sphere_num]);for (int i = 0, t = 0; i < sphere_num; ++i, t += 3) {spheres[i].r = a[t];spheres[i].g = a[t + 1];spheres[i].b = a[t + 2];spheres[i].x = b[t];spheres[i].y = b[t + 1];spheres[i].z = b[t + 2];spheres[i].radius = c[i];}// cudaMalloc: 在设备端分配内存cudaMalloc(&dev_image, length);// method1: 没有使用常量内存//Sphere* dev_spheres{ nullptr };//cudaMalloc(&dev_spheres, sizeof(Sphere) * sphere_num);/* cudaMemcpy: 在主机端和设备端拷贝数据,此函数第四个参数仅能是下面之一:(1). cudaMemcpyHostToHost: 拷贝数据从主机端到主机端(2). cudaMemcpyHostToDevice: 拷贝数据从主机端到设备端(3). cudaMemcpyDeviceToHost: 拷贝数据从设备端到主机端(4). cudaMemcpyDeviceToDevice: 拷贝数据从设备端到设备端(5). cudaMemcpyDefault: 从指针值自动推断拷贝数据方向,需要支持统一虚拟寻址(CUDA6.0及以上版本)cudaMemcpy函数对于主机是同步的 *///cudaMemcpy(dev_spheres, spheres.get(), sizeof(Sphere) * sphere_num, cudaMemcpyHostToDevice);// method2: 使用常量内存/* cudaMemcpyToSymbol: cudaMemcpyToSymbol和cudaMemcpy参数为cudaMemcpyHostToDevice时的唯一差异在于cudaMemcpyToSymbol会复制到常量内存,而cudaMemcpy会复制到全局内存*/cudaMemcpyToSymbol(dev_spheres, spheres.get(), sizeof(Sphere)* sphere_num);const int threads_block{ 16 };dim3 blocks(width / threads_block, height / threads_block);dim3 threads(threads_block, threads_block);/* <<< >>>: 为CUDA引入的运算符,指定线程网格和线程块维度等,传递执行参数给CUDA编译器和运行时系统,用于说明内核函数中的线程数量,以及线程是如何组织的;尖括号中这些参数并不是传递给设备代码的参数,而是告诉运行时如何启动设备代码,传递给设备代码本身的参数是放在圆括号中传递的,就像标准的函数调用一样;不同计算能力的设备对线程的总数和组织方式有不同的约束;必须先为kernel中用到的数组或变量分配好足够的空间,再调用kernel函数,否则在GPU计算时会发生错误,例如越界等;使用运行时API时,需要在调用的内核函数名与参数列表直接以<<<Dg,Db,Ns,S>>>的形式设置执行配置,其中: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型变量,指定各块为此调用动态分配的共享存储器大小,这些动态分配的存储器可供声明为外部数组(extern __shared__)的其他任何变量使用;Ns是一个可选参数,默认值为0;S为cudaStream_t类型,用于设置与内核函数关联的流.S是一个可选参数,默认值0. *///ray_tracking << <blocks, threads >> >(dev_image, dev_spheres, width, height, sphere_num); // method1, 不使用常量内存ray_tracking << <blocks, threads >> >(dev_image, width, height, sphere_num); // method2, 使用常量内存cudaMemcpy(ptr, dev_image, length, cudaMemcpyDeviceToHost);// cudaFree: 释放设备上由cudaMalloc函数分配的内存cudaFree(dev_image);//cudaFree(dev_spheres); // 使用method1时需要释放, 如果使用常量内存即method2则不需要释放// cudaEventRecord: 记录一个事件,异步启动,stop记录结束时间cudaEventRecord(stop, 0);// cudaEventSynchronize: 事件同步,等待一个事件完成,异步启动cudaEventSynchronize(stop);// cudaEventElapseTime: 计算两个事件之间经历的时间,单位为毫秒,异步启动cudaEventElapsedTime(elapsed_time, start, stop);// cudaEventDestroy: 销毁事件对象,异步启动cudaEventDestroy(start);cudaEventDestroy(stop);return 0;
}

生成的结果图像如下:

执行结果如下:可见使用C++和CUDA实现的结果是完全一致的。

GitHub:  https://github.com/fengbingchun/CUDA_Test

CUDA Samples: Ray Tracking相关推荐

  1. CUDA Samples: 获取设备属性信息

    通过调用CUDA的cudaGetDeviceProperties函数可以获得指定设备的相关信息,此函数会根据GPU显卡和CUDA版本的不同得到的结果也有所差异,下面code列出了经常用到的设备信息: ...

  2. CUDA Samples: matrix multiplication(C = A * B)

    以下CUDA sample是分别用C++和CUDA实现的两矩阵相乘运算code即C= A*B,CUDA中包含了两种核函数的实现方法,第一种方法来自于CUDA Samples\v8.0\0_Simple ...

  3. CUDA Samples:Vector Add

    以下CUDA sample是分别用C++和CUDA实现的两向量相加操作,参考CUDA 8.0中的sample:C:\ProgramData\NVIDIA Corporation\CUDA Sample ...

  4. 安装cuda后却没有CUDA Samples怎么办?

    Cuda 11.6版本之后将不再编译cuda,所以必须自己从github下载后自行编译, 下载网址为 cuda samples 对于windows用户, Windows示例是使用Visual Stud ...

  5. CUDA Samples 之 Simulations 之 Particles (1)

    CUDA Samples 之 Simulations 之 Particles源码学习(1) 自己用C++编程做颗粒堆积,但效率很低,所以想将程序并行,所以开始接触CUDA.但是完全不知道如何搭一个并行 ...

  6. run cuda samples ubuntu_NVIDIA cuDNN v8 deb方法安装教程(Linux/Ubuntu)

    0 deb和tar方法 为什么推荐使用deb方法呢,因为下面三点: 使用tar方法安装不会有cudnn_samples_v8这个文件,无法使用官方的安装完成验证方式. 查看cuDNN的方法已经过时了, ...

  7. CUDA Samples

    最近准备再挖个坑,翻译下cuda_samples,给入门想看代码又不知道看点啥的小同学提供一些指引(顺便指引下自己).本文简要介绍samples里的项目的主要功能. 简介 Simple Referen ...

  8. CUDA Samples目录

    简介 Simple Reference  基础CUDA示例,适用于初学者, 反映了运用CUDA和CUDA runtime APIs的一些基本概念. Utilities Reference  演示如何查 ...

  9. CUDA Samples: Image Process: BGR to BGR565

    图像像素格式BGR565是每一个像素占2个字节,其中Blue占5位,Green占6位,Red占5位.在OpenCV中,BGR到BGR565的每一个像素的计算公式是: unsigned short ds ...

最新文章

  1. 驱动学习之LED驱动框架
  2. Opengl编程学习笔记(五)——从FRAGMENT到PIXEL(framebuffer 帧缓存)
  3. 深度丨110亿美金还不够,阿里使用这种AI手段创造更多广告收入
  4. iOS之仿QQ点赞按钮粒子效果的实现
  5. enter opportunity line item detail page AG3
  6. html文字列表,文字列表模板
  7. c++矩阵类_面向对象有限元编程|单元类
  8. java plug机制_插件机制 - OpooPress - 基于 Java 的静态博客生成器
  9. 知方可补不足~数据库名称和数据库别名不同了怎么办
  10. .net core 调用c dll_C++ 调用C封装DLL库的两种方式
  11. ++i和i++哪个效率更高
  12. java读取文件buffered_关于Java中使用BufferedReader读取文件的疑惑
  13. 我的世界JAVA会支持光追吗_我的世界怎么开启光追
  14. java加密与解密-核心包中的部分API(2)
  15. 塔夫斯大学计算机专业,塔夫茨大学优势专业
  16. excel 电阻并联计算_3个并联电阻计算公式 并联电阻计算公式计算方法
  17. 你知道吗?什么是 Responsive JavaScript ?
  18. 光年(Light Year Admin)后台管理系统模板
  19. SOCKS5实现代理服务器(C++)
  20. 爬虫实战-python爬取QQ群好友信息

热门文章

  1. python基础知识整理 第三节 :函数
  2. 【神经网络】(6) 卷积神经网络(VGG16),案例:鸟类图片4分类
  3. linux系统重装后挂载数据盘,Linux重装系统后如何重新挂载数据盘?
  4. java list 拼音排序_java中实现List集合中对象元素按其属性的中文拼音排序
  5. android的xml置底_Android布局之xml设置
  6. opencv c++ 寻找矩形框_基于Python的OpenCV人脸检测!OpenCV太强了!
  7. CMRNet++:一种相机在激光雷达构建地图中的定位方案
  8. 解决360浏览器偶发性会闪屏一下黑色的背景
  9. Linux 下获取本机所有网卡 以及 网卡对应ip 列表
  10. 数据库 大数据访问及分区分块优化方案