GPGPU OpenCL编程步骤与简单实例
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编程步骤与简单实例的更多相关文章
- Win Socket编程原理及简单实例
[转]http://www.cnblogs.com/tornadomeet/archive/2012/04/11/2442140.html 使用Linux Socket做了小型的分布式,如Linux ...
- Linux C Socket编程原理及简单实例
部分转自:http://goodcandle.cnblogs.com/archive/2005/12/10/294652.aspx 1. 什么是TCP/IP.UDP? 2. Socket在哪里 ...
- JNA的步骤、简单实例以及资料整理
1.步骤 1.编写dll文件,放入项目的bin目录(在window上是dll文件,在Linux上是so文件,dll和so都是由C程序生成) 2.新建接口继承Library 3.加载对应的dll或者 ...
- 简单的JDBC编程步骤
1.加载数据库驱动(com.mysql.jdbc.Driver) 2.创建并获取数据库链接(Connection) 3.创建jdbc statement对象(PreparedStatement) 4. ...
- 【并行计算-CUDA开发】GPGPU OpenCL/CUDA 高性能编程的10大注意事项
GPGPU OpenCL/CUDA 高性能编程的10大注意事项 1.展开循环 如果提前知道了循环的次数,可以进行循环展开,这样省去了循环条件的比较次数.但是同时也不能使得kernel代码太大. 循环展 ...
- Win32 API 多线程编程——一个简单实例(含消息参数传递)
Win32 API进行程序设计具有很多优点:应用程序执行代码小,运行效率高,但是他要求程序员编写的代码较多,且需要管理所有系统提供给程序的资源,要求程序员对Windows系统内核有一定的了解,会占用程 ...
- Hibernate(二)__简单实例入门
首先我们进一步理解什么是对象关系映射模型? 它将对数据库中数据的处理转化为对对象的处理.如下图所示: 入门简单实例: hiberante 可以用在 j2se 项目,也可以用在 j2ee (web项目中 ...
- Docker初步认识安装和简单实例
前话 问题 开发网站需要搭建服务器环境,FQ官网下载软件包,搭建配置nginx,apache,数据库等.官网没有直接可用的运行版本,担心网络流传的非官方发布软件包不安全还得自行编译官方源码安装,忘记步 ...
- C++网络套接字编程TCP和UDP实例
原文地址:C++网络套接字编程TCP和UDP实例作者:xiaojiangjiang 1. 创建一个简单的SOCKET编程流程如下 面向有连接的套接字编程 服务器: 1) 创建套接字(so ...
随机推荐
- Django学习笔记-2018.11.16
知识储备: 1 Python基础 2 数据库SQL 3 HTTP协议 4 HTML&&CSS 5 正则表达式 Django启动 django-admin startproject pr ...
- JOYOI 西瓜种植 [差分约束系统]
题目传送门 西瓜种植 题目限制 时间限制 内存限制 评测方式 题目来源 1000ms 131072KiB 标准比较器 Local 题目背景 笨笨:小西瓜,小西瓜~路人甲:不会呀,这西瓜明明就大着啊…… ...
- Spring框架 AOP面向切面编程(转)
一.前言 在以前的项目中,很少去关注spring aop的具体实现与理论,只是简单了解了一下什么是aop具体怎么用,看到了一篇博文写得还不错,就转载来学习一下,博文地址:http://www.cnbl ...
- 最短路——spfa
适用范围:给定的图存在负权边,这时类似Dijkstra等算法便没有了用武之地,而Bellman-Ford算法的复杂度又过高,SPFA算法便派上用场了. 我们约定有向加权图G不存在负权回路,即最短路径一 ...
- 20162325 金立清 S2 W6 C15
20162325 2017-2018-2 <程序设计与数据结构>第6周学习总结 教材学习内容概要 队列是先进先出(FIFO)的集合 队列是保存重复编码k值的一种有效结构 实现模拟时常用队列 ...
- Unity 播放音频文件
Unity 播放音频文件参考代码: public void Play(string strSoundName, float autoDestroyTime = 0f, bool bLoop = fal ...
- 线段树--codevs 1690 开关灯
codevs 1690 开关灯 USACO 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 钻石 Diamond 题目描述 Description YYX家门前的街上有N(2& ...
- bzoj4034 树上操作
Description 有一棵点数为 N 的树,以点 1 为根,且树点有边权.然后有 M 个 操作,分为三种: 操作 1 :把某个节点 x 的点权增加 a . 操作 2 :把某个节点 x 为根的子树中 ...
- Theme.AppCompat无全屏主题解决办法
V7包中的Theme.AppCompat主题系列中并没有全屏样式,这个是为什么,只有作者知道…… 解决办法: 自定义主题 <style name="Theme.AppCompat.Li ...
- 使用Spring配置shiro时,自定义Realm中属性无法使用注解注入解决办法
先来看问题 纠结了几个小时终于找到了问题所在,因为shiro的realm属于Filter,简单说就是初始化realm时,spring还未加载相关业务Bean,那么解决办法就是将springmvc ...