http://www.cnblogs.com/xudong-bupt/p/3582780.html 

1.OpenCL概念

  OpenCL是一个为异构平台编写程序的框架,此异构平台可由CPU、GPU或其他类型的处理器组成。OpenCL由一门用于编写kernels (在OpenCL设备上运行的函数)的语言(基于C99)和一组用于定义并控制平台的API组成。

  OpenCL提供了两种层面的并行机制:任务并行与数据并行。

2.OpenCL与CUDA的区别

  不同点:OpenCL是通用的异构平台编程语言,为了兼顾不同设备,使用繁琐。

      CUDA是nvidia公司发明的专门在其GPGPU上的编程的框架,使用简单,好入门。

  相同点:都是基于任务并行与数据并行。

3.OpenCL的编程步骤

  (1)Discover and initialize the platforms

    调用两次clGetPlatformIDs函数,第一次获取可用的平台数量,第二次获取一个可用的平台。

  (2)Discover and initialize the devices

    调用两次clGetDeviceIDs函数,第一次获取可用的设备数量,第二次获取一个可用的设备。

  (3)Create  a context(调用clCreateContext函数)

    上下文context可能会管理多个设备device。

  (4)Create a command queue(调用clCreateCommandQueue函数)

    一个设备device对应一个command queue。

    上下文conetxt将命令发送到设备对应的command queue,设备就可以执行命令队列里的命令。

  (5)Create device buffers(调用clCreateBuffer函数)

    Buffer中保存的是数据对象,就是设备执行程序需要的数据保存在其中。

    Buffer由上下文conetxt创建,这样上下文管理的多个设备就会共享Buffer中的数据。

  (6)Write host data to device buffers(调用clEnqueueWriteBuffer函数)

  (7)Create and compile the program

    创建程序对象,程序对象就代表你的程序源文件或者二进制代码数据。

  (8)Create the kernel(调用clCreateKernel函数)

    根据你的程序对象,生成kernel对象,表示设备程序的入口。

  (9)Set the kernel arguments(调用clSetKernelArg函数)

  (10)Configure the work-item structure(设置worksize)

    配置work-item的组织形式(维数,group组成等)

  (11)Enqueue the kernel for execution(调用clEnqueueNDRangeKernel函数)

    将kernel对象,以及 work-item参数放入命令队列中进行执行。

  (12)Read  the output buffer back to the host(调用clEnqueueReadBuffer函数)

  (13)Release OpenCL resources(至此结束整个运行过程)

4.说明

  OpenCL中的核函数必须单列一个文件。

  OpenCL的编程一般步骤就是上面的13步,太长了,以至于要想做个向量加法都是那么困难。

  不过上面的步骤前3步一般是固定的,可以单独写在一个.h/.cpp文件中,其他的一般也不会有什么大的变化。

5.程序实例,向量运算

5.1通用前3个步骤,生成一个文件

  tool.h

 #ifndef TOOLH
#define TOOLH #include <CL/cl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <fstream>
using namespace std; /** convert the kernel file into a string */
int convertToString(const char *filename, std::string& s); /**Getting platforms and choose an available one.*/
int getPlatform(cl_platform_id &platform); /**Step 2:Query the platform and choose the first GPU device if has one.*/
cl_device_id *getCl_device_id(cl_platform_id &platform); #endif

  tool.cpp

 #include <CL/cl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <fstream>
#include "tool.h"
using namespace std; /** convert the kernel file into a string */
int convertToString(const char *filename, std::string& s)
{
size_t size;
char* str;
std::fstream f(filename, (std::fstream::in | std::fstream::binary)); if(f.is_open())
{
size_t fileSize;
f.seekg(, std::fstream::end);
size = fileSize = (size_t)f.tellg();
f.seekg(, std::fstream::beg);
str = new char[size+];
if(!str)
{
f.close();
return ;
} f.read(str, fileSize);
f.close();
str[size] = '\0';
s = str;
delete[] str;
return ;
}
cout<<"Error: failed to open file\n:"<<filename<<endl;
return -;
} /**Getting platforms and choose an available one.*/
int getPlatform(cl_platform_id &platform)
{
platform = NULL;//the chosen platform cl_uint numPlatforms;//the NO. of platforms
cl_int status = clGetPlatformIDs(, NULL, &numPlatforms);
if (status != CL_SUCCESS)
{
cout<<"Error: Getting platforms!"<<endl;
return -;
} /**For clarity, choose the first available platform. */
if(numPlatforms > )
{
cl_platform_id* platforms =
(cl_platform_id* )malloc(numPlatforms* sizeof(cl_platform_id));
status = clGetPlatformIDs(numPlatforms, platforms, NULL);
platform = platforms[];
free(platforms);
}
else
return -;
} /**Step 2:Query the platform and choose the first GPU device if has one.*/
cl_device_id *getCl_device_id(cl_platform_id &platform)
{
cl_uint numDevices = ;
cl_device_id *devices=NULL;
cl_int status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, , NULL, &numDevices);
if (numDevices > ) //GPU available.
{
devices = (cl_device_id*)malloc(numDevices * sizeof(cl_device_id));
status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, numDevices, devices, NULL);
}
return devices;
}

5.2核函数文件

  HelloWorld_Kernel.cl

 __kernel void helloworld(__global double* in, __global double* out)
{
int num = get_global_id();
out[num] = in[num] / 2.4 *(in[num]/) ;
}

5.3主函数文件

  HelloWorld.cpp

 //For clarity,error checking has been omitted.
#include <CL/cl.h>
#include "tool.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <fstream>
using namespace std; int main(int argc, char* argv[])
{
cl_int status;
/**Step 1: Getting platforms and choose an available one(first).*/
cl_platform_id platform;
getPlatform(platform); /**Step 2:Query the platform and choose the first GPU device if has one.*/
cl_device_id *devices=getCl_device_id(platform); /**Step 3: Create context.*/
cl_context context = clCreateContext(NULL,, devices,NULL,NULL,NULL); /**Step 4: Creating command queue associate with the context.*/
cl_command_queue commandQueue = clCreateCommandQueue(context, devices[], , NULL); /**Step 5: Create program object */
const char *filename = "HelloWorld_Kernel.cl";
string sourceStr;
status = convertToString(filename, sourceStr);
const char *source = sourceStr.c_str();
size_t sourceSize[] = {strlen(source)};
cl_program program = clCreateProgramWithSource(context, , &source, sourceSize, NULL); /**Step 6: Build program. */
status=clBuildProgram(program, ,devices,NULL,NULL,NULL); /**Step 7: Initial input,output for the host and create memory objects for the kernel*/
const int NUM=;
double* input = new double[NUM];
for(int i=;i<NUM;i++)
input[i]=i;
double* output = new double[NUM]; cl_mem inputBuffer = clCreateBuffer(context, CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR, (NUM) * sizeof(double),(void *) input, NULL);
cl_mem outputBuffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY , NUM * sizeof(double), NULL, NULL); /**Step 8: Create kernel object */
cl_kernel kernel = clCreateKernel(program,"helloworld", NULL); /**Step 9: Sets Kernel arguments.*/
status = clSetKernelArg(kernel, , sizeof(cl_mem), (void *)&inputBuffer);
status = clSetKernelArg(kernel, , sizeof(cl_mem), (void *)&outputBuffer); /**Step 10: Running the kernel.*/
size_t global_work_size[] = {NUM};
cl_event enentPoint;
status = clEnqueueNDRangeKernel(commandQueue, kernel, , NULL, global_work_size, NULL, , NULL, &enentPoint);
clWaitForEvents(,&enentPoint); ///wait
clReleaseEvent(enentPoint); /**Step 11: Read the cout put back to host memory.*/
status = clEnqueueReadBuffer(commandQueue, outputBuffer, CL_TRUE, , NUM * sizeof(double), output, , NULL, NULL);
cout<<output[NUM-]<<endl; /**Step 12: Clean the resources.*/
status = clReleaseKernel(kernel);//*Release kernel.
status = clReleaseProgram(program); //Release the program object.
status = clReleaseMemObject(inputBuffer);//Release mem object.
status = clReleaseMemObject(outputBuffer);
status = clReleaseCommandQueue(commandQueue);//Release Command queue.
status = clReleaseContext(context);//Release context. if (output != NULL)
{
free(output);
output = NULL;
} if (devices != NULL)
{
free(devices);
devices = NULL;
}
return ;
}

编译、链接、执行:

  g++ -I /opt/AMDAPP/include/ -o A  *.cpp -lOpenCL ; ./A

  

GPGPU OpenCL编程步骤与简单实例的更多相关文章

  1. Win Socket编程原理及简单实例

    [转]http://www.cnblogs.com/tornadomeet/archive/2012/04/11/2442140.html 使用Linux Socket做了小型的分布式,如Linux ...

  2. Linux C Socket编程原理及简单实例

    部分转自:http://goodcandle.cnblogs.com/archive/2005/12/10/294652.aspx 1.   什么是TCP/IP.UDP? 2.   Socket在哪里 ...

  3. JNA的步骤、简单实例以及资料整理

    1.步骤 1.编写dll文件,放入项目的bin目录(在window上是dll文件,在Linux上是so文件,dll和so都是由C程序生成)  2.新建接口继承Library  3.加载对应的dll或者 ...

  4. 简单的JDBC编程步骤

    1.加载数据库驱动(com.mysql.jdbc.Driver) 2.创建并获取数据库链接(Connection) 3.创建jdbc statement对象(PreparedStatement) 4. ...

  5. 【并行计算-CUDA开发】GPGPU OpenCL/CUDA 高性能编程的10大注意事项

    GPGPU OpenCL/CUDA 高性能编程的10大注意事项 1.展开循环 如果提前知道了循环的次数,可以进行循环展开,这样省去了循环条件的比较次数.但是同时也不能使得kernel代码太大. 循环展 ...

  6. Win32 API 多线程编程——一个简单实例(含消息参数传递)

    Win32 API进行程序设计具有很多优点:应用程序执行代码小,运行效率高,但是他要求程序员编写的代码较多,且需要管理所有系统提供给程序的资源,要求程序员对Windows系统内核有一定的了解,会占用程 ...

  7. Hibernate(二)__简单实例入门

    首先我们进一步理解什么是对象关系映射模型? 它将对数据库中数据的处理转化为对对象的处理.如下图所示: 入门简单实例: hiberante 可以用在 j2se 项目,也可以用在 j2ee (web项目中 ...

  8. Docker初步认识安装和简单实例

    前话 问题 开发网站需要搭建服务器环境,FQ官网下载软件包,搭建配置nginx,apache,数据库等.官网没有直接可用的运行版本,担心网络流传的非官方发布软件包不安全还得自行编译官方源码安装,忘记步 ...

  9. C++网络套接字编程TCP和UDP实例

    原文地址:C++网络套接字编程TCP和UDP实例作者:xiaojiangjiang 1.       创建一个简单的SOCKET编程流程如下 面向有连接的套接字编程 服务器: 1)  创建套接字(so ...

随机推荐

  1. ELK系列--问题汇总(二)

    1.Kibana4 dashboard无法保存拖动的visualization位置 原因: 程序bug,json部分未能及时保存拖动的情况 解决方法: 手动在设置中,手动编辑dashboard的jso ...

  2. oracle去掉字段值中的某些字符串

    我想去掉字段值中的“_” select replace(fdisplayname,'_','') from SHENZHENJM1222.B replace 第一个参数:字段/值,第二个参数时替换字符 ...

  3. 【Python初级】由判定回文数想到的,关于深浅复制,以及字符串反转的问题

    尝试用Python实现可以说是一个很经典的问题,判断回文数. 让我们再来看看回文数是怎么定义的: 回数是指从左向右读和从右向左读都是一样的数,例如1,121,909,666等 解决这个问题的思路,可以 ...

  4. HDU 6060 RXD and dividing(dfs 思维)

    RXD and dividing Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 524288/524288 K (Java/Other ...

  5. python的进阶--爬虫小试

    代理之说 [ python实现代理服务功能实例 ]  --  https://www.jb51.net/article/43266.htm [检测代理是否有效] -- https://blog.csd ...

  6. Unity Shader 之 渲染流水线

    Unity Shader 之渲染流水线 什么是渲染流水线 一个渲染流程分成3个步骤: 应用阶段(Application stage) 几何阶段(Geometry stage) 光栅化阶段(Raster ...

  7. 管理openstack多region介绍与实践

    转:http://www.cnblogs.com/zhoumingang/p/5514853.html 概念介绍 所谓openstack多region,就是多套openstack共享一个keyston ...

  8. Redis学习篇(十二)之管道技术

    通过管道技术降低往返时延 当后一条命令不依赖于前一条命令的返回结果时,可以使用管道技术将多条命令一起 发送给redis服务器,服务器执行结束之后,一起返回结果,降低了通信频度.

  9. [BZOJ1791][IOI2008]Island岛屿(环套树DP)

    同NOI2013快餐店(NOI出原题?),下面代码由于BZOJ栈空间过小会RE. 大致是对每个连通块找到环,在所有内向树做一遍DP,再在环上做两遍前缀和优化的DP. #include<cstdi ...

  10. SQL的in的参数化查询

    SqlCommand cmd=con.CreateCommand(); cmd.CommandText="exec('select * from novel where novelid in ...