homer512 icon

OpenCL enum devices

homer512 | PRO | 08/13/16 09:20:56 AM UTC | 0 ⭐ | 710 👁️ | Never ⏰ | []
C |

2.29 KB

|

None

|

0 👍

/

0 👎

#include <cl.h>
/* using cl_* */
 
#include <stdlib.h>
/* using malloc, free */
#include <stdio.h>
/* using printf */
 
 
static cl_int get_platforms(cl_platform_id** ids, cl_uint* count)
{
  cl_int rtrn;
  if((rtrn = clGetPlatformIDs(0, NULL, count)) != CL_SUCCESS)
    return rtrn;
  if(! *count) {
    *ids = NULL;
    return rtrn;
  }
  if(! (*ids = malloc(*count * sizeof(**ids))))
    return CL_OUT_OF_HOST_MEMORY;
  if((rtrn = clGetPlatformIDs(*count, *ids, count)) != CL_SUCCESS)
    free(*ids);
  return rtrn;
}
 
static cl_int get_devices(cl_platform_id platform, cl_device_id** ids, cl_uint* count)
{
  cl_int rtrn;
  if((rtrn = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 0, NULL, count)) != CL_SUCCESS)
    return rtrn;
  if(! *count) {
    *ids = NULL;
    return rtrn;
  }
  if(! (*ids = malloc(*count * sizeof(**ids))))
    return CL_OUT_OF_HOST_MEMORY;
  if((rtrn = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, *count, *ids, count)) != CL_SUCCESS)
    free(*ids);
  return rtrn;
}
 
static cl_int get_device_name(cl_device_id device, char** name)
{
  cl_int rtrn;
  size_t size;
  if((rtrn = clGetDeviceInfo(device, CL_DEVICE_NAME, 0, NULL, &size)) != CL_SUCCESS)
    return rtrn;
  if(! (*name = malloc(size)))
    return CL_OUT_OF_HOST_MEMORY;
  if((rtrn = clGetDeviceInfo(device, CL_DEVICE_NAME, size, *name, &size)) != CL_SUCCESS)
    free(*name);
  return rtrn;
}
 
static cl_int print_device_names(void)
{
  cl_platform_id* platforms;
  cl_uint platform_count, platform;
  cl_device_id* devices;
  cl_int rtrn;
  if((rtrn = get_platforms(&platforms, &platform_count)) != CL_SUCCESS)
    return rtrn;
  for(platform = 0; platform < platform_count; ++platform) {
    cl_uint device_count, device;
    if((rtrn = get_devices(platforms[platform], &devices, &device_count)) != CL_SUCCESS)
      goto free_platforms;
    for(device = 0; device < device_count; ++device) {
      char* name;
      if((rtrn = get_device_name(devices[device], &name)) != CL_SUCCESS)
        goto free_devices;
      printf("%s\n", name);
      free(name);
    }
    free(devices);
  }
  goto free_platforms;
 free_devices:
  free(devices);
 free_platforms:
  free(platforms);
  return rtrn;
}
  
int main(void)
{
  return print_device_names() == CL_SUCCESS ? 0 : 1;
}

Comments