opencl初体验

总结一下,opencl的步骤差不多是这些

先要获取平台的id clGetPlatformIDs(nPlatforms, platform_id, &num_of_platforms)

然后获取设备id clGetDeviceIDs(platform_id[1], CL_DEVICE_TYPE_GPU, 1, %device_id &num_of_devices)

////这里要注意的是,如果有多个设备(如cpu和gpu)platform_id必须使用数组形式传入

然后是创建上下文clCreateContext(properties, 1, &device_id, NULL, NULL, &err)

创建命令队列clCreateCommandQueue(context, device_id, 0, &err)

创建设备缓存clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float) * DATA_SIZE, NULL, NULL);

复制数据clEnqueueWriteBuffer(command_queue, input, CL_TRUE, 0, sizeof(float)*DATA_SIZE, inputData, 0, NULL, NULL)

然后是根据源代码产生program代码 clCreateProgramWithSource(context, 1, (const char **)&ProgramSource, NULL, &err)

然后编译program clBuildProgram(program, 0, NULL, NULL, NULL, NULL)

最后产生kernel clCreateKernel(program, "test", &err);

设定kernel的参数 clSetKernelArg(kernel, 0, sizeof(cl_mem), &input)

将kernel推入命令队列 clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global, NULL, 0, NULL, NULL)

完成计算clFinish(command_queue)

读取设备缓存clEnqueueReadBuffer(command_queue, input, CL_TRUE, 0, sizeof(float) * DATA_SIZE, inputData, 0, NULL, NULL)

最后是清理工作

clReleaseMemObject(input)

clReleaseProgram(program)

clReleaseKernel(kernel)

clReleaseCommandQueue(command_queue)

clReleaseContext(context)

大致是这个流程,详细每个命令的参数怎么设定还要看文档

https://www.khronos.org/registry/cl/sdk/1.1/docs/man/xhtml/

出了任何报错最好还是查一下头文件,很有帮助

原文地址:https://www.cnblogs.com/sickboy/p/4415746.html