以下CUDA sample是分别用C++和CUDA实现的生成的绿色的球图像,并对其中使用到的CUDA函数进行了解说,code参考了《GPU高性能编程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_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 }; // milliseconds

	int 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__: 函数类型限定符;在设备上运行;在主机端调用,计算能力3.2及以上可以在
设备端调用;声明的函数的返回值必须是void类型;对此类型函数的调用是异步的,即在
设备完全完成它的运行之前就返回了;对此类型函数的调用必须指定执行配置,即用于在
设备上执行函数时的grid和block的维度,以及相关的流(即插入<<<   >>>运算符);
a kernel,表示此函数为内核函数(运行在GPU上的CUDA并行计算函数称为kernel(内核函
数),内核函数必须通过__global__函数类型限定符定义); */
__global__ static void green_ball(unsigned char* ptr, int width, int height)
{
	/* 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 position
	int 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内的所有线程访问;__shared__和__constant__变量
	默认为是静态存储;在__shared__前可以加extern关键字,但表示的是变量大小
	由执行参数确定;__shared__变量在声明时不能初始化;可以将CUDA C的关键字
	__shared__添加到变量声明中,这将使这个变量驻留在共享内存中;CUDA C编译
	器对共享内存中的变量与普通变量将分别采取不同的处理方式 */
	__shared__ float shared[16][16]; // == threads_block

	// now calculate the value at that position
	const 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架构将确保,除非线程块
	中的每个线程都执行了__syncthreads(),否则没有任何线程能执行
	__syncthreads()之后的指令;在同一个block中的线程通过共享存储器(shared
	memory)交换数据,并通过栅栏同步(可以在kernel函数中需要同步的位置调用
	__syncthreads()函数)保证线程间能够正确地共享数据;使用clock()函数计时,
	在内核函数中要测量的一段代码的开始和结束的位置分别调用一次clock()函数,
	并将结果记录下来。由于调用__syncthreads()函数后,一个block中的所有
	thread需要的时间是相同的,因此只需要记录每个block执行需要的时间就行了,
	而不需要记录每个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,结构体类型, 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{ nullptr };
	// cudaMalloc: 在设备端分配内存
	cudaMalloc(&dev, length);

	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. */
	green_ball << <blocks, threads >> >(dev, width, height);

	/* cudaMemcpy: 在主机端和设备端拷贝数据,此函数第四个参数仅能是下面之一:
	(1). cudaMemcpyHostToHost: 拷贝数据从主机端到主机端
	(2). cudaMemcpyHostToDevice: 拷贝数据从主机端到设备端
	(3). cudaMemcpyDeviceToHost: 拷贝数据从设备端到主机端
	(4). cudaMemcpyDeviceToDevice: 拷贝数据从设备端到设备端
	(5). cudaMemcpyDefault: 从指针值自动推断拷贝数据方向,需要支持
	统一虚拟寻址(CUDA6.0及以上版本)
	cudaMemcpy函数对于主机是同步的 */
	cudaMemcpy(ptr, dev, length, cudaMemcpyDeviceToHost);

	// cudaFree: 释放设备上由cudaMalloc函数分配的内存
	cudaFree(dev);

	// cudaEventRecord: 记录一个事件,异步启动,stop记录结束时间
	cudaEventRecord(stop, 0);
	// cudaEventSynchronize: 事件同步,等待一个事件完成,异步启动
	cudaEventSynchronize(stop);
	// cudaEventElapseTime: 计算两个事件之间经历的时间,单位为毫秒,异步启动
	cudaEventElapsedTime(elapsed_time, start, stop);
	// cudaEventDestroy: 销毁事件对象,异步启动
	cudaEventDestroy(start);
	cudaEventDestroy(stop);

	return 0;
}

生成的结果图像如下:


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

CUDA Samples: green ball的更多相关文章

  1. CUDA samples 2.3节 用CUDA示例来创建CUDA项目

    2.3.1. Creating CUDA Projects for Windows 略 2.3.2  Creating CUDA Projects for Linux 默认的samples的安装路径 ...

  2. CUDA samples 第三章 sample reference 概况

    示例代码分为下列几类: 1.   Simple Reference 基础CUDA示例,适用于初学者, 反应了运用CUDA和CUDA runtime APIs的一些基本概念. 2.   Utilitie ...

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

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

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

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

  5. CUDA Samples:Vector Add

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

  6. CUDA Samples: dot product(使用零拷贝内存)

    以下CUDA sample是分别用C++和CUDA实现的点积运算code,CUDA包括普通实现和采用零拷贝内存实现两种,并对其中使用到的CUDA函数进行了解说,code参考了<GPU高性能编程C ...

  7. CUDA Samples: Streams' usage

    以下CUDA sample是分别用C++和CUDA实现的流的使用code,并对其中使用到的CUDA函数进行了解说,code参考了<GPU高性能编程CUDA实战>一书的第十章,各个文件内容如 ...

  8. CUDA Samples: Calculate Histogram(atomicAdd)

    以下CUDA sample是分别用C++和CUDA实现的计算一维直方图,并对其中使用到的CUDA函数进行了解说,code参考了<GPU高性能编程CUDA实战>一书的第九章,各个文件内容如下 ...

  9. CUDA Samples: heat conduction(模拟热传导)

    以下CUDA sample是分别用C++和CUDA实现的模拟热传导生成的图像,并对其中使用到的CUDA函数进行了解说,code参考了<GPU高性能编程CUDA实战>一书的第七章,各个文件内 ...

随机推荐

  1. jenkins邮箱配置以及结合ansible进行批量构建

    tomcat8.5以上版本,jenkins2.7以上版本 首先填写你的系统管理员邮件地址,否则会使用jenkins系统本身的邮箱 填写的163邮箱,通过smtp认证填写正确的账号和密码(注意这里的密码 ...

  2. mysql备份脚本-mysqldump

    背景:全库备份 备份流程: 1.生成DB列表,将DB名字写入文件 2.定义备份函数,结果写入SQL文件 3.压缩文件,减少磁盘占用量 4.设置保留天数,定期删除n天之前的 5.通过for循环读取DB列 ...

  3. <The old man and the sea>

    Every day is a new day. It is better to be lucky. But i would rather be exact. Then when luck comes ...

  4. PAT1072. Gas Station (30)

    题目的测试用例数据有问题! 第一个Case 应该是 G1 2.0 3.2 一直在想3.3分母的3怎么来了.ORZ #include <iostream> #include <ccty ...

  5. GridView绑定数据源 绑定DataReader /DataSet /DataTable

    有一个GridView1 <asp:GridView ID="GridView1" runat="server"></asp:GridView ...

  6. cocos2d-x入门二 helloworld实例运行与创建

    本机环境:win7+VS2012+python2.7.8+cocos2d-x-3.8,另外本机已经配置android开发环境(java+eclipse+SDK+ADT),针对环境搭建后续会有一篇详细说 ...

  7. 上传网站后建议执行:chown www:www -R /path/to/dir 对网站目录进行权限设置,/path/to/dir替换为你网站目录。

    上传网站后建议执行:chown www:www -R /path/to/dir 对网站目录进行权限设置,/path/to/dir替换为你网站目录.

  8. IntelliJ IDEA 左侧显示/展开类中的方法

    困扰我很久的问题: project直接右键: 打开.关闭对应效果: 之前查到的都是 : 虽然也有类似的功能,但是展开的是右侧窗口中,打开的那个类的: 即使不是我想要的,但也是不错的功能!

  9. torch 深度学习(3)

    torch 深度学习(3) 损失函数,模型训练 前面我们已经完成对数据的预处理和模型的构建,那么接下来为了训练模型应该定义模型的损失函数,然后使用BP算法对模型参数进行调整 损失函数 Criterio ...

  10. node-glob 匹配通配符

    1.https://www.cnblogs.com/liulangmao/p/4552339.html 2.https://github.com/isaacs/node-glob 3.https:// ...