在opencl编程中,很多时候需要初始化很多东西,比如查询设备,选择计算设备,初始化上下文,构建程序和编译内核程序。如果每次都重写写一遍这些过程,就会感动很繁琐,所以,我就简单封装了几个函数,用于我的opencl编程中。关于从文本文件构建opencl程序在OpenCL从文本文件构建程序对象已经讲解,下面就给出初始化opencl,以及构建程序和编译内核程序的源代码:
void OpenCLInit(cl_platform_id *clPlatform ,cl_device_id *clDevice,cl_context *clContext) { cl_uint numPlatforms = 0; //GPU计算平台个数 cl_platform_id platform = NULL; clGetPlatformIDs(0,NULL,&numPlatforms); //获得平台列表 cl_platform_id * platforms = (cl_platform_id*)malloc(numPlatforms * sizeof(cl_platform_id)); clGetPlatformIDs (numPlatforms, platforms, NULL); //轮询各个opencl设备 for (cl_uint i = 0; i < numPlatforms; i ++) { char pBuf[100]; clGetPlatformInfo(platforms[i],CL_PLATFORM_VERSION,sizeof(pBuf),pBuf,NULL); printf("%s\n",pBuf); platform = platforms[i]; //break; } *clPlatform = platform; free(platforms); cl_int status = 0; //获得GPU设备 cl_device_id device; status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL); *clDevice = device; //生成上下文 cl_context context = clCreateContext(0, 1, &device, NULL, NULL, &status); *clContext = context; }
构建程序的函数封装如下:
void BuildKernel(cl_platform_id platform , cl_device_id device, cl_context context, cl_program *clProgram, cl_command_queue *clCommandQueue) { cl_int status = 0; //装载内核程序 size_t szKernelLength = 0; const char* kernelSourceCode = LoadProgSource(cSourceFile, "", &szKernelLength); cl_program program = clCreateProgramWithSource(context,1,&kernelSourceCode,&szKernelLength,&status); *clProgram = program; //为所有指定的设备生成CL_program status = clBuildProgram(program,1,&device,NULL,NULL,NULL); size_t len = 0; char buf[2048]; if (status != CL_SUCCESS) { status = clGetProgramBuildInfo(program,device,CL_PROGRAM_BUILD_LOG,sizeof(buf),buf,&len); printf("%s\n", buf); } //创建一个opencl命令队列 *clCommandQueue = clCreateCommandQueue(context,device,0,&status); }
希望对大家有用