在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);
}
希望對大家有用