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 ...
随机推荐
- vue 分页插件
有个小问题就是最多显示3个分页,可以手动改一下配置参数就好.直接代码: <template> <div class="pageination_align"> ...
- Redis Cluster集群的搭建与实践
Redis Cluster集群 一.redis-cluster设计 Redis集群搭建的方式有多种,例如使用zookeeper等,但从redis 3.0之后版本支持redis-cluster集群,Re ...
- chakra在vs2017中编译出现的问题
转:http://blog.csdn.net/ink_cherry/article/details/73437981 1.无法找到vs2010生成工具 MSB8020 无法找到 Visual Stud ...
- iOS 9音频应用播放音频之第一个ios9音频实例
iOS 9音频应用播放音频之第一个ios9音频实例 第一个ios9音频实例 为了让开发者可以对上面的内容有更加深入的了解,本节将实现播放音频的第一个实例.在此实例中会涉及到项目的创建.界面设计.关联以 ...
- onvif 开发中的一些重要函数介绍
➤soap结构中count(soap->count)成员 soap结构中count(soap->count)成员记录的是http协议中Content-Length的数值. ➤keep_al ...
- python解决组合问题
1.问题描述 比如9个数中取4个数的组合以及列出各种组合,该如何做? 我们可以考虑以下一个简单组合:从1,2,3,4,5,6中,如何选取任意四个数的组合. 固定:1 2 3 ,组合有1234 ...
- VS2015快捷键及常用功能
写下这些快捷键的操作,并不是全部记住,记住常用的,然后其他的来查询就好了. 1.回到上一个光标位置/前进到下一个光标位置 1)回到上一个光标位置:使用组合键“Ctrl + -”; 2)前进到下一个光标 ...
- NOI2005 维护数列(splay)
学了半天平衡树,选择了一道题来写一写,发现题目是裸的splay模板,但是还是写不好,这个的精髓之处在于在数列的某一个位置加入一个数列,类似于treap里面的merge,然后还学到了题解里面的的回收空间 ...
- [BZOJ4887][TJOI2017]可乐(DP+矩阵快速幂)
题目描述 加里敦星球的人们特别喜欢喝可乐.因而,他们的敌对星球研发出了一个可乐机器人,并且放在了加里敦星球的1号城市上.这个可乐机器人有三种行为: 停在原地,去下一个相邻的城市,自爆.它每一秒都会随机 ...
- bzoj 4097: [Usaco2013 dec]Vacation Planning
4097: [Usaco2013 dec]Vacation Planning Description Air Bovinia is planning to connect the N farms (1 ...