欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

OpenCL编程详细解析与实例

发布时间:2023/11/28 38 豆豆
生活随笔 收集整理的这篇文章主要介绍了 OpenCL编程详细解析与实例 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

OpenCL编程详细解析与实例
C语言与OpenCL的编程示例比较
参考链接:
https://www.zhihu.com/people/wujianming_110117/posts
先以图像旋转的实例,具体介绍OpenCL编程的步骤。 首先给出实现流程,然后给出实现图像旋转的C循环实现和OpenCL C kernel实现。
图像旋转原理
图像旋转是指把定义的图像绕某一点以逆时针或顺时针方向旋转一定的角度, 通常是指绕图像的中心以逆时针方向旋转。假设图像的左上角为(l, t), 右下角为(r, b),则图像上任意点(x, y) 绕其中心(xcenter, ycenter)逆时针旋转θ角度后, 新的坐标位置(x’,y’)的计算公式为:
x′ = (x - xcenter) cosθ - (y - ycenter) sinθ + xcenter,
y′ = (x - xcenter) sinθ + (y - ycenter) cosθ + ycenter.
C代码:
void rotate(
unsigned char* inbuf,
unsigned char* outbuf,
int w, int h,
float sinTheta,
float cosTheta)
{
int i, j;
int xc = w/2;
int yc = h/2;
for(i = 0; i < h; i++)
{
for(j=0; j< w; j++)
{
int xpos = (j-xc)cosTheta - (i - yc) * sinTheta + xc;
int ypos = (j-xc)sinTheta + (i - yc) * cosTheta + yc;
if(xpos>=0&&ypos>=0&&xpos<w&&ypos<h)
outbuf[ypos
w + xpos] = inbuf[i
w+j];
}
}
}

OpenCL C kernel代码:
#pragma OPENCL EXTENSION cl_amd_printf : enable
__kernel void image_rotate(
__global uchar * src_data,
__global uchar * dest_data, //Data in global memory
int W, int H, //Image Dimensions
float sinTheta, float cosTheta ) //Rotation Parameters
{
const int ix = get_global_id(0);
const int iy = get_global_id(1);
int xc = W/2;
int yc = H/2;
int xpos = ( ix-xc)*cosTheta - (iy-yc)*sinTheta+xc;
int ypos = (ix-xc)sinTheta + ( iy-yc)cosTheta+yc;
if ((xpos>=0) && (xpos< W) && (ypos>=0) && (ypos< H))
dest_data[ypos
W+xpos]= src_data[iy
W+ix];
}

正如上面代码中所给出的那样,在C代码中需要两重循环来计算横纵坐标上新的 坐标位置。其实,在图像旋转的算法中每个点的计算可以独立进行,与其它点的 坐标位置没有关系,所以并行处理较为方便。OpenCL C kernel代码中用了并行 处理。
上面的代码在Intel的OpenCL平台上进行了测试,处理器为双核处理器,图像大小 为4288*3216,如果用循环的方式运行时间稳定在0.256s左右,而如果用OpenCL C kernel并行的方式,运行时间稳定在0.132秒左右。GPU的测试在NVIDIA的GeForce G105M显卡 上进行,运行时间稳定在0.0810s左右。从循环的方式,双核CPU并行以及GPU并行计算 已经可以看出,OpenCL编程的确能大大提高执行效率。
OpenCL编程详细解析
OpenCL作为一门开源的异构并行计算语言,设计之初就是使用一种模型来模糊各种硬件差异。作为软件开发人员,关注的就是编程模型。OpenCL程序的流程大致如下:
• Platform
• 查询并选择一个 platform
• 在 platform 上创建 context
• 在 context 上查询并选择一个或多个 device
• Running time
• 加载 OpenCL 内核程序并创建一个 program 对象
• 为指定的 device 编译 program 中的 kernel
• 创建指定名字的 kernel 对象
• 为 kernel 创建内存对象
• 为 kernel 设置参数
• 在指定的 device 上创建 command queue
• 将要执行的 kernel 放入 command queue
• 将结果读回 host
• 资源回收
模块分析
使用 OpenCL API 编程与一般 C/C++ 引入第三方库编程没什么区别。所以,首先要做的自然是 include 相关的头文件。由于在 MacOS X 10.6下OpenCL的头文件命名与其他系统不同,通常使用一个#if defined进行区分,代码如下:

  1. #if defined(APPLE) || defined(__MACOSX)
  2. #include <OpenCL/cl.hpp>
  3. #else
  4. #include <CL/cl.h>
  5. #endif
    接下来就进入真正的编码流程了。
    Platform
    查询并选择一个 platform
    首先要取得系统中所有的 OpenCL platform。所谓的 platform 指的就是硬件厂商提供的 OpenCL 框架,不同的 CPU/GPU 开发商(比如 Intel、AMD、Nvdia)可以在一个系统上分别定义自己的 OpenCL 框架。所以需要查询系统中可用的 OpenCL 框架,即 platform。使用 API 函数 clGetPlatformIDs 获取可用 platform 的数量:
  6. cl_int status = 0;
  7. cl_uint numPlatforms;
  8. cl_platform_id platform = NULL;
  9. status = clGetPlatformIDs( 0, NULL, &numPlatforms);
  10. if(status != CL_SUCCESS){
  11.  printf("Error: Getting Platforms\n");
    
  12.  return EXIT_FAILURE;
    
  13. }
    然后根据数量来分配内存,并得到所有可用的 platform,所使用的 API 还是clGetPlatformIDs。在 OpenCL 中,类似这样的函数调用很常见:第一次调用以取得数目,便于分配足够的内存;然后调用第二次以获取真正的信息。
  14. if (numPlatforms > 0) {
  15.  cl_platform_id *platforms = (cl_platform_id *)malloc(numPlatforms * sizeof(cl_platform_id));
    
  16.  status = clGetPlatformIDs(numPlatforms, platforms, NULL);
    
  17.  if (status != CL_SUCCESS) {
    
  18.      printf("Error: Getting Platform Ids.(clGetPlatformIDs)\n");
    
  19.      return -1;
    
  20.  }
    

现在,所有的 platform 都存在了变量 platforms 中,接下来需要做的就是取得所需的 platform。本人的PC上配置的是 Intel 处理器和 AMD 显卡,专业点的说法叫 Intel 的 CPU 和 NVIDIA的 GPU 😃。所以这儿有两套 platform,为了体验下 GPU 的快感,所以使用 AMD 的 platform。通过使用 clGetPlatformInfo 来获得 platform 的信息。通过这个 API 可以知晓 platform 的厂商信息,以便选出需要的 platform。代码如下:

  1. for (unsigned int i = 0; i < numPlatforms; ++i) {
  2.      char pbuff[100];
    
  3.      status = clGetPlatformInfo(
    
  4.                   platforms[i],
    
  5.                   CL_PLATFORM_VENDOR,
    
  6.                   sizeof(pbuff),
    
  7.                   pbuff,
    
  8.                   NULL);
    
  9.      platform = platforms[i];
    
  10.     if (!strcmp(pbuff, "Advanced Micro Devices, Inc.")) {
    
  11.         break;
    
  12.     }
    
  13. }
    

不同的厂商信息可以参考 OpenCL Specifications,这儿只是简单的筛选出 AMD 。
在 platform 上建立 context
第一步是通过 platform 得到相应的 context properties

  1. // 如果能找到相应平台,就使用,否则返回NULL
  2. cl_context_properties cps[3] = {
  3.  CL_CONTEXT_PLATFORM,
    
  4.  (cl_context_properties)platform,
    
  5.  0
    
  6. };
  7. cl_context_properties *cprops = (NULL == platform) ? NULL : cps;
    第二步是通过 clCreateContextFromType 函数创建 context。
  8. // 生成 context
  9. cl_context context = clCreateContextFromType(
  10.                       cprops,
    
  11.                       CL_DEVICE_TYPE_GPU,
    
  12.                       NULL,
    
  13.                       NULL,
    
  14.                       &status);
    
  15. if (status != CL_SUCCESS) {
  16.  printf("Error: Creating Context.(clCreateContexFromType)\n");
    
  17. return EXIT_FAILURE;
    
  18. }
    函数的第二个参数可以设定 context 关联的设备类型。本例使用的是 GPU 作为OpenCL计算设备。目前可以使用的类别包括:
    • CL_DEVICE_TYPE_CPU
    • CL_DEVICE_TYPE_GPU
    • CL_DEVICE_TYPE_ACCELERATOR
    • CL_DEVICE_TYPE_DEFAULT
    • CL_DEVICE_TYPE_ALL
      在 context 上查询 device
      context 创建好之后,要做的就是查询可用的 device。
  19. status = clGetContextInfo(context,
  20.                        CL_CONTEXT_DEVICES,
    
  21.                        0,
    
  22.                        NULL,
    
  23.                        &deviceListSize);
    
  24. if (status != CL_SUCCESS) {
  25.  printf("Error: Getting Context Info device list size, clGetContextInfo)\n");
    
  26.  return EXIT_FAILURE;
    
  27. }
  28. cl_device_id *devices = (cl_device_id *)malloc(deviceListSize);
  29. if (devices == 0) {
  30. printf("Error: No devices found.\n");
    
  31. return EXIT_FAILURE;
    
  32. }
  33. status = clGetContextInfo(context,
  34.                       CL_CONTEXT_DEVICES,
    
  35.                       deviceListSize,
    
  36.                       devices,
    
  37.                       NULL);
    
  38. if (status != CL_SUCCESS) {
  39. printf("Error: Getting Context Info (device list, clGetContextInfo)\n");
    
  40. return EXIT_FAILURE;
    
  41. }
    与获取 platform 类似,调用两次 clGetContextInfo 来完成 查询。第一次调用获取关联 context 的 device 个数,并根据个数申请内存;第二次调用获取所有 device 实例。如果想了解每个 device 的具体信息,可以调用 clGetDeviceInfo 函数来获取,返回的信息有设备类型、生产商以及设备对某些扩展功能的支持与否等等。详细使用情况请参阅 OpenCL Specifications。
    到此,platform 相关的程序已经准备就绪了,下面到此的完整代码:
  42. /* OpenCL_01.cpp
    • © by keyring keyrings@163.com
    • 2013.10.26
  43. */
  44. #if defined(APPLE) || defined(__MACOSX)
  45. #include <OpenCL/cl.hpp>
  46. #else
  47. #include <CL/cl.h>
  48. #endif
  49. #include
  50. int main(int argc, char const *argv[])
  51. {
  52. printf("hello OpenCL\n");
    
  53. cl_int status = 0;
    
  54. size_t deviceListSize;
    
  55. // 得到并选择可用平台
    
  56. cl_uint numPlatforms;
    
  57. cl_platform_id platform = NULL;
    
  58. status = clGetPlatformIDs(0, NULL, &numPlatforms);
    
  59. if (status != CL_SUCCESS) {
    
  60.     printf("ERROR: Getting Platforms.(clGetPlatformIDs)\n");
    
  61.     return EXIT_FAILURE;
    
  62. }
    
  63. if (numPlatforms > 0) {
    
  64.     cl_platform_id *platforms = (cl_platform_id *)malloc(numPlatforms * sizeof(cl_platform_id));
    
  65.     status = clGetPlatformIDs(numPlatforms, platforms, NULL);
    
  66.     if (status != CL_SUCCESS) {
    
  67.         printf("Error: Getting Platform Ids.(clGetPlatformIDs)\n");
    
  68.         return -1;
    
  69.     }
    
  70.     // 遍历所有 platform,选择想用的
    
  71.     for (unsigned int i = 0; i < numPlatforms; ++i) {
    
  72.         char pbuff[100];
    
  73.         status = clGetPlatformInfo(
    
  74.                      platforms[i],
    
  75.                      CL_PLATFORM_VENDOR,
    
  76.                      sizeof(pbuff),
    
  77.                      pbuff,
    
  78.                      NULL);
    
  79.         platform = platforms[i];
    
  80.         if (!strcmp(pbuff, "Advanced Micro Devices, Inc.")) {
    
  81.             break;
    
  82.         }
    
  83.     }
    
  84.     delete platforms;
    
  85. }
    
  86. // 如果能找到相应平台,就使用,否则返回NULL
    
  87. cl_context_properties cps[3] = {
    
  88.     CL_CONTEXT_PLATFORM,
    
  89.     (cl_context_properties)platform,
    
  90.     0
    
  91. };
    
  92. cl_context_properties *cprops = (NULL == platform) ? NULL : cps;
    
  93. // 生成 context
    
  94. cl_context context = clCreateContextFromType(
    
  95.                          cprops,
    
  96.                          CL_DEVICE_TYPE_GPU,
    
  97.                          NULL,
    
  98.                          NULL,
    
  99.                          &status);
    
  100. if (status != CL_SUCCESS) {
    
  101.     printf("Error: Creating Context.(clCreateContexFromType)\n");
    
  102.     return EXIT_FAILURE;
    
  103. }
    
  104. // 寻找OpenCL设备
    
  105. // 首先得到设备列表的长度
    
  106. status = clGetContextInfo(context,
    
  107.                           CL_CONTEXT_DEVICES,
    
  108.                           0,
    
  109.                           NULL,
    
  110.                           &deviceListSize);
    
  111. if (status != CL_SUCCESS) {
    
  112.     printf("Error: Getting Context Info device list size, clGetContextInfo)\n");
    
  113.     return EXIT_FAILURE;
    
  114. }
    
  115. cl_device_id *devices = (cl_device_id *)malloc(deviceListSize);
    
  116. if (devices == 0) {
    
  117.     printf("Error: No devices found.\n");
    
  118.     return EXIT_FAILURE;
    
  119. }
    
  120. // 然后得到设备列表
    
  121. status = clGetContextInfo(context,
    
  122.                           CL_CONTEXT_DEVICES,
    
  123.                           deviceListSize,
    
  124.                              devices,
    
  125.                              NULL);
    
  126.    if (status != CL_SUCCESS) {
    
  127.        printf("Error: Getting Context Info (device list, clGetContextInfo)\n");
    
  128.        return EXIT_FAILURE;
    
  129.    }
    

Running time
前面写了这么多,其实还没真正进入具体的程序逻辑中,顶多算配好了 OpenCL 运行环境。真正的逻辑代码,即程序的任务就是运行时模块。本例的任务是在一个 4×4的二维空间上,按一定的规则给每个元素赋值,具体代码如下:

  1. #define KERNEL(…)#VA_ARGS
  2. const char *kernelSourceCode = KERNEL(
  3.                                 __kernel void hellocl(__global uint *buffer)
    
  4. {
  5.  size_t gidx = get_global_id(0);
    
  6.  size_t gidy = get_global_id(1);
    
  7.  size_t lidx = get_local_id(0);
    
  8.  buffer[gidx + 4 * gidy] = (1 << gidx) | (0x10 << gidy);
    
  9. }
  10.                            );
    

这一段就是真正的逻辑,也就是代码要干的事。使用的是 OpenCL 自定的一门类C语言,具体的语法什么的现在先不纠结。这段代码是直接嵌入 cpp 文件的静态字符串。也可以将 kernel 程序单独写成一个文件。
加载 OpenCL 内核程序并创建一个 program 对象
接下来要做的就是读入 OpenCL kernel 程序并创建一个 program 对象。

  1. size_t sourceSize[] = {strlen(kernelSourceCode)};
  2. cl_program program = clCreateProgramWithSource(context,
  3.                   1,
    
  4.                   &kernelSourceCode,
    
  5.                   sourceSize,
    
  6.                   &status);
    
  7. if (status != CL_SUCCESS) {
  8.  printf("Error: Loading Binary into cl_program (clCreateProgramWithBinary)\n");
    
  9.  return EXIT_FAILURE;
    
  10. }
    本例中的 kernel 程序是作为静态字符串读入的(单独的文本文件也一样),所以使用的是 clCreateProgramWithSource,如果不想让 kernel 程序让其他人看见,可以先生成二进制文件,再通过 clCreateProgramWithBinary 函数动态读入二进制文件,做一定的保密。详细请参阅 OpenCL Specifications。
    为指定的 device 编译 program 中的 kernel
    kernel 程序读入完毕,要做的自然是使用 clBuildProgram 编译 kernel:
  11. status = clBuildProgram(program, 1, devices, NULL, NULL, NULL);
  12. if (status != CL_SUCCESS) {
  13.  printf("Error: Building Program (clBuildingProgram)\n");
    
  14.  return EXIT_FAILURE;
    
  15. }
    最终,kernel 将被相应 device 上的 OpenCL 编译器编译成可执行的机器码。
    创建指定名字的 kernel 对象
    成功编译后,可以通过 clCreateKernel 来创建一个 kernel 对象。
  16. cl_kernel kernel = clCreateKernel(program, “hellocl”, &status);
  17. if (status != CL_SUCCESS) {
  18.  printf("Error: Creating Kernel from program.(clCreateKernel)\n");
    
  19.  return EXIT_FAILURE;
    
  20. }
    引号中的 hellocl 就是 kernel 对象所关联的 kernel 函数的函数名。要注意的是,每个 kernel 对象必须关联且只能关联一个包含于相应 program 对象内的 kernel 程序。实际上,用户可以在 cl 源代码中写任意多个 kernel 程序,但在执行某个 kernel 程序之前必须先建立单独的 kernel 对象,即多次调用 clCreateKernel 函数。
    为 kernel 创建内存对象
    OpenCL 内存对象是指在 host 中创建,用于 kernel 程序的内存类型。按维度可以分为两类,一类是 buffer,一类是 image。buffer 是一维的,image 可以是二维、三维的 texture、frame-buffer 或 image。本例仅仅使用 buffer,可以通过clCreateBuffer 函数来创建。
  21. cl_mem outputBuffer = clCreateBuffer(
  22.                                  context, 
    
  23.                                  CL_MEM_ALLOC_HOST_PTR, 
    
  24.                                  4 * 4 * 4, 
    
  25.                                  NULL, 
    
  26.                                  &status);
    
  27. if (status != CL_SUCCESS) {
  28.  printf("Error: Create Buffer, outputBuffer. (clCreateBuffer)\n");
    
  29.  return EXIT_FAILURE;
    
  30. }
    为 kernel 设置参数
    使用 clSetKernelArg 函数为 kernel 设置参数。传递的参数既可以是常数,变量,也可以是内存对象。本例传递的就是内存对象。
  31. status = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&outputBuffer);
  32. if (status != CL_SUCCESS) {
  33.  printf("Error: Setting kernel argument. (clSetKernelArg)\n");
    
  34.  return EXIT_FAILURE;
    
  35. }
    该函数每次只能设置一个参数,如有多个参数,需多次调用。而且 kernel 程序中所有的参数都必须被设置,否则在启动 kernel 程序是会报错。指定位置的参数的类型最好和对应 kernel 函数内参数类型一致,以免产生各种未知的错误。在设置好指定参数后,每次运行该 kernel 程序都会使用设置值,直到用户使用次 API 重新设置参数。
    在指定的 device 上创建 command queue
    command queue 用于光里将要执行的各种命令。可以通过 clCreateCommandQueue函数创建。其中的 device 必须为 context 的关联设备,所有该 command queue 中的命令都会在这个指定的 device 上运行。
  36. cl_command_queue commandQueue = clCreateCommandQueue(context,
  37.                              devices[0],
    
  38.                              0,
    
  39.                              &status);
    
  40. if (status != CL_SUCCESS) {
  41.  printf("Error: Create Command Queue. (clCreateCommandQueue)\n");
    
  42.  return EXIT_FAILURE;
    
  43. }
    将要执行的 kernel 放入 command queue
    创建好 command queue 后,用户可以创建相应的命令并放入 command queue 中执行。OpenCL 提供了三种方案来创建 kernel 执行命令。最常用的即为本例所示的运行在指定工作空间上的 kernel 程序,使用了 clEnqueueNDRangeKernel 函数。
  44. size_t globalThreads[] = {4, 4};
  45. size_t localThreads[] = {2, 2};
  46. status = clEnqueueNDRangeKernel(commandQueue, kernel,
  47.                              2, NULL, globalThreads,
    
  48.                              localThreads, 0,
    
  49.                              NULL, NULL);
    
  50. if (status != CL_SUCCESS) {
  51.  printf("Error: Enqueueing kernel\n");
    
  52.  return EXIT_FAILURE;
    
  53. }
    clEnqueueNDRangeKernel 函数每次只能将一个 kernel 对象放入 command queue 中,用户可以多次调用该 API 将多个 kernel 对象放置到一个 command queue 中,command queue 中的不同 kernel 对象的工作区域完全不相关。其余两个 APIclEnqueueTask 和 clEnqueueNativeKernel 的用法就不多讲了,详情请参阅OpenCL Specificarions。
    最后可以用 clFinish 函数来确认一个 command queue 中所有的命令都执行完毕。函数会在 command queue 中所有 kernel 执行完毕后返回。
  54. // 确认 command queue 中所有命令都执行完毕
  55. status = clFinish(commandQueue);
  56. if (status != CL_SUCCESS) {
  57.  printf("Error: Finish command queue\n");
    
  58.  return EXIT_FAILURE;
    
  59. }
    将结果读回 host
    计算完毕,将结果读回 host 端。使用 clEnqueueReadBuffer 函数将 OpenCL buffer 对象中的内容读取到 host 可以访问的内存空间。
  60. // 将内存对象中的结果读回Host
  61. status = clEnqueueReadBuffer(commandQueue,
  62.                           outputBuffer, CL_TRUE, 0,
    
  63.                           4 * 4 * 4, outbuffer, 0, NULL, NULL);
    
  64. if (status != CL_SUCCESS) {
  65.  printf("Error: Read buffer queue\n");
    
  66.  return EXIT_FAILURE;
    
  67. }
    当然,为了看下程序的运行效果,咱们当然得看看运行结果啦。打印一下吧:
  68. // Host端打印结果
  69. printf(“out:\n”);
  70. for (int i = 0; i < 16; ++i) {
  71.  printf("%x ", outbuffer[i]);
    
  72.  if ((i + 1) % 4 == 0)
    
  73.      printf("\n");
    
  74. }
    资源回收
    程序的最后是对所有创建的对象进行释放回收,与C/C++的内存回收同理。
  75. // 资源回收
  76. status = clReleaseKernel(kernel);
  77. status = clReleaseProgram(program);
  78. status = clReleaseMemObject(outputBuffer);
  79. status = clReleaseCommandQueue(commandQueue);
  80. status = clReleaseContext(context);
  81. free(devices);
  82. delete outbuffer;
    总结
    这次使用一个小例子来详细说明了 OpenCL 编程的一般步骤。其实这些步骤一般都是固定的。真正需要注意的是 OpenCL Kernel 程序的编写。当然,合理高效的利用 API 也是一门技术活。
    完整程序
  83. #include
  84. #include <stdlib.h>
  85. #include <string.h>
  86. #include <stdio.h>
  87. #if defined(APPLE) || defined(__MACOSX)
  88. #include <OpenCL/cl.hpp>
  89. #else
  90. #include <CL/cl.h>
  91. #endif
  92. using namespace std;
  93. #define KERNEL(…)#VA_ARGS
  94. const char *kernelSourceCode = KERNEL(
  95.                                __kernel void hellocl(__global uint *buffer)
    
  96. {
  97. size_t gidx = get_global_id(0);
    
  98. size_t gidy = get_global_id(1);
    
  99. size_t lidx = get_local_id(0);
    
  100. buffer[gidx + 4 * gidy] = (1 << gidx) | (0x10 << gidy);
    
  101. }
  102.                            );
    
  103. int main(int argc, char const *argv[])
  104. {
  105. printf("hello OpenCL\n");
    
  106. cl_int status = 0;
    
  107. size_t deviceListSize;
    
  108. // 当前服务器上配置的仅有NVIDIA Tesla C2050 的GPU
    
  109. cl_platform_id platform = NULL;
    
  110. status = clGetPlatformIDs(1, &platform, NULL);
    
  111. if (status != CL_SUCCESS) {
    
  112.     printf("ERROR: Getting Platforms.(clGetPlatformIDs)\n");
    
  113.     return EXIT_FAILURE;
    
  114. }
    
  115. // 如果能找到相应平台,就使用,否则返回NULL
    
  116. cl_context_properties cps[3] = {
    
  117.     CL_CONTEXT_PLATFORM,
    
  118.     (cl_context_properties)platform,
    
  119.     0
    
  120. };
    
  121. cl_context_properties *cprops = (NULL == platform) ? NULL : cps;
    
  122. // 生成 context
    
  123. cl_context context = clCreateContextFromType(
    
  124.                          cprops,
    
  125.                          CL_DEVICE_TYPE_GPU,
    
  126.                          NULL,
    
  127.                          NULL,
    
  128.                          &status);
    
  129. if (status != CL_SUCCESS) {
    
  130.     printf("Error: Creating Context.(clCreateContexFromType)\n");
    
  131.     return EXIT_FAILURE;
    
  132. }
    
  133. // 寻找OpenCL设备
    
  134. // 首先得到设备列表的长度
    
  135. status = clGetContextInfo(context,
    
  136.                           CL_CONTEXT_DEVICES,
    
  137.                           0,
    
  138.                           NULL,
    
  139.                           &deviceListSize);
    
  140. if (status != CL_SUCCESS) {
    
  141.     printf("Error: Getting Context Info device list size, clGetContextInfo)\n");
    
  142.     return EXIT_FAILURE;
    
  143. }
    
  144. cl_device_id *devices = (cl_device_id *)malloc(deviceListSize);
    
  145. if (devices == 0) {
    
  146.     printf("Error: No devices found.\n");
    
  147.     return EXIT_FAILURE;
    
  148. }
    
  149. // 现在得到设备列表
    
  150. status = clGetContextInfo(context,
    
  151.                           CL_CONTEXT_DEVICES,
    
  152.                           deviceListSize,
    
  153.                           devices,
    
  154.                           NULL);
    
  155. if (status != CL_SUCCESS) {
    
  156.     printf("Error: Getting Context Info (device list, clGetContextInfo)\n");
    
  157.     return EXIT_FAILURE;
    
  158. }
    
  159. // 装载内核程序,编译CL program ,生成CL内核实例
    
  160. size_t sourceSize[] = {strlen(kernelSourceCode)};
    
  161. cl_program program = clCreateProgramWithSource(context,
    
  162.                      1,
    
  163.                         &kernelSourceCode,
    
  164.                         sourceSize,
    
  165.                         &status);
    
  166.    if (status != CL_SUCCESS) {
    
  167.        printf("Error: Loading Binary into cl_program (clCreateProgramWithBinary)\n");
    
  168.        return EXIT_FAILURE;
    
  169.    }
    
  170.    // 为指定的设备编译CL program.
    
  171.    status = clBuildProgram(program, 1, devices, NULL, NULL, NULL);
    
  172.    if (status != CL_SUCCESS) {
    
  173.        printf("Error: Building Program (clBuildingProgram)\n");
    
  174.        return EXIT_FAILURE;
    
  175.    }
    
  176.    // 得到指定名字的内核实例的句柄
    
  177.    cl_kernel kernel = clCreateKernel(program, "hellocl", &status);
    
  178.    if (status != CL_SUCCESS) {
    
  179.        printf("Error: Creating Kernel from program.(clCreateKernel)\n");
    
  180.        return EXIT_FAILURE;
    
  181.    }
    
  182.    // 创建 OpenCL buffer 对象
    
  183.    unsigned int *outbuffer = new unsigned int [4 * 4];
    
  184.    memset(outbuffer, 0, 4 * 4 * 4);
    
  185.    cl_mem outputBuffer = clCreateBuffer(
    
  186.        context, 
    
  187.        CL_MEM_ALLOC_HOST_PTR, 
    
  188.        4 * 4 * 4, 
    
  189.        NULL, 
    
  190.        &status);
    
  191.    if (status != CL_SUCCESS) {
    
  192.        printf("Error: Create Buffer, outputBuffer. (clCreateBuffer)\n");
    
  193.        return EXIT_FAILURE;
    
  194.    }
    
  195.    //  为内核程序设置参数
    
  196.    status = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&outputBuffer);
    
  197.    if (status != CL_SUCCESS) {
    
  198.        printf("Error: Setting kernel argument. (clSetKernelArg)\n");
    
  199.        return EXIT_FAILURE;
    
  200.    }
    
  201.    // 创建一个OpenCL command queue
    
  202.    cl_command_queue commandQueue = clCreateCommandQueue(context,
    
  203.                                    devices[0],
    
  204.                                    0,
    
  205.                                    &status);
    
  206.    if (status != CL_SUCCESS) {
    
  207.        printf("Error: Create Command Queue. (clCreateCommandQueue)\n");
    
  208.        return EXIT_FAILURE;
    
  209.    }
    
  210.    // 将一个kernel 放入 command queue
    
  211.    size_t globalThreads[] = {4, 4};
    
  212.    size_t localThreads[] = {2, 2};
    
  213.    status = clEnqueueNDRangeKernel(commandQueue, kernel,
    
  214.                                    2, NULL, globalThreads,
    
  215.                                    localThreads, 0,
    
  216.                                    NULL, NULL);
    
  217.    if (status != CL_SUCCESS) {
    
  218.        printf("Error: Enqueueing kernel\n");
    
  219.        return EXIT_FAILURE;
    
  220.    }
    
  221.    // 确认 command queue 中所有命令都执行完毕
    
  222.    status = clFinish(commandQueue);
    
  223.    if (status != CL_SUCCESS) {
    
  224.        printf("Error: Finish command queue\n");
    
  225.        return EXIT_FAILURE;
    
  226.    }
    
  227.    // 将内存对象中的结果读回Host
    
  228.    status = clEnqueueReadBuffer(commandQueue,
    
  229.                                 outputBuffer, CL_TRUE, 0,
    
  230.                                 4 * 4 * 4, outbuffer, 0, NULL, NULL);
    
  231.    if (status != CL_SUCCESS) {
    
  232.        printf("Error: Read buffer queue\n");
    
  233.        return EXIT_FAILURE;
    
  234.    }
    
  235.    // Host端打印结果
    
  236.    printf("out:\n");
    
  237.    for (int i = 0; i < 16; ++i) {
    
  238.        printf("%x ", outbuffer[i]);
    
  239.        if ((i + 1) % 4 == 0)
    
  240.            printf("\n");
    
  241.    }
    
  242.    // 资源回收
    
  243.    status = clReleaseKernel(kernel);
    
  244.    status = clReleaseProgram(program);
    
  245.    status = clReleaseMemObject(outputBuffer);
    
  246.    status = clReleaseCommandQueue(commandQueue);
    
  247.    status = clReleaseContext(context);
    
  248.    free(devices);
    
  249.    delete outbuffer;
    
  250.    return 0;
    
  251. }
    运行结果

参考链接:
https://www.zhihu.com/people/wujianming_110117/posts
https://blog.csdn.net/fly_yr/article/details/51259692
https://www.cnblogs.com/wangshide/archive/2012/01/07/2315830.html

总结

以上是生活随笔为你收集整理的OpenCL编程详细解析与实例的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。