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 ...
随机推荐
- Spring Boot 整合MyBatis(1)
这篇文章介绍如何在Spring boot中整合Mybatis,其中sql语句采用注解的方式插入.后续文章将会介绍,如何使用xml方式. SSM SSH框架已经满足轻量级这个需求了,但是对于开发人员而言 ...
- 验证码无法显示:Could not initialize class sun.awt.X11GraphicsEnvironment 解决方案
一.原因现象:图下图 二.原因导致: 经过Google发现很多人也出现同样的问题.从了解了X11GraphicEnvironment这个类的功能入手,一个Java服务器来处理图片的API基本上是需要运 ...
- Angular部署到windows上
1. 确保已经打开了IIS服务. 如果没有打开可参考 http://jingyan.baidu.com/article/eb9f7b6d9e73d1869364e8d8.html 2. 编译angul ...
- Web应用安全审计工具WATOBO
Web应用安全审计工具WATOBO WATOBO是一款Web应用程序安全测试工具.该工具使用代理方式,对Web会话数据进行审计.它是一款半自动化工具,可以自动对请求和响应进行分析,找出潜在漏洞信息 ...
- Mac os 下的文件权限管理
Mac os 下的文件权限管理 命令 ls -l -A 结果 -rw-r--r-- 1 user admin 2326156 4 12 15:24 adb 横线代表空许可.r代表只读,w代表写,x代表 ...
- Python中yield和yield from的用法
yield python中yield的用法很像return,都是提供一个返回值,但是yield和return的最大区别在于,return一旦返回,则代码段执行结束,但是yield在返回值以后,会交出C ...
- 1.6(SQL学习笔记)存储过程
一.什么事存储过程 可以将存储过程看做是一组完成某个特定功能的SQL语句的集合. 例如有一个转账功能(A向B转账50),先将账户A中金额扣除50,然后将账户B中金额添加50. 那么我们可以定义一个名为 ...
- 快速幂 cojs 1130. 取余运算
cojs 1130. 取余运算 ★ 输入文件:dmod.in 输出文件:dmod.out 简单对比时间限制:10 s 内存限制:128 MB [题目描述] 输入b,p,k的值,求b^p ...
- 参加SAP VT项目有感
凡事预则立,不预则废. 没有接到录取电话还是有些悲伤的,虽然知道最终被录取的可能性不大,但是之前还是抱着一丝期望的,毕竟是自己的处女面,就这么以失败的结果结束了. 从最开始的投递简历,到后来的电话面试 ...
- TPS61175/TPS55340 3A/5A、40V 电流模式集成 FET 升压 DC/DC 转换器
集成型5A 40V 宽输入范围升压/单端初级电感转换器(SEPIC) / 反激式(Flyback) 直流到直流稳压器 (Rev. B) 描述 TPS55340 是一款单片非同步开关稳压器,此稳压器带有 ...