OpenCL


Overview 

Introduction
  • Hello OpenCL
  • 
    // Hello World for OpenCL
    // Copyright 2009 David Black-Schaffer
    //
    
    #include "OpenCL/opencl.h"
    #include 
    #include 
    
    #define LENGTH 10240
    
    
    // Define our kernel. It just calculates the sin of the input data.
    char *source = {
     "kernel calcSin(global float *data) {\n"
     "  int id = get_global_id(0);\n"
     "  data[id] = sin(data[id]);\n"
     "}\n"
    };
    
    // Note: there is no error handling here. This is bad practice in general.
    
    int main (int argc, const char * argv[]) {
     
     // OpenCL Objects
     cl_device_id device;
     cl_context context;
     cl_command_queue queue;
     cl_program program;
     cl_kernel kernel;
     cl_mem buffer; 
     
     
     
     // Create and initialize the input data
     cl_float *data;
     data = (cl_float*)malloc(sizeof(cl_float)*LENGTH);
    
     for (int i=0; iLENGTH; i++) 
     {
      data[i] = i;
     }
     
     
     
     // Setup OpenCL
     clGetDeviceIDs(NULL, CL_DEVICE_TYPE_DEFAULT, 1, &device, NULL);
     context = clCreateContext(NULL, 1, &device, NULL, NULL, NULL);
     queue = clCreateCommandQueue(context, device, (cl_command_queue_properties)0, NULL);
     
     
     
     // Setup the input
     buffer = clCreateBuffer(context, CL_MEM_COPY_HOST_PTR, sizeof(cl_float)*10240, data, NULL);
     
     
     
     // Build the kernel
     program = clCreateProgramWithSource(context, 1, (const char**)&source, NULL, NULL);
     clBuildProgram(program, 0, NULL, NULL, NULL, NULL);
     kernel = clCreateKernel(program, "calcSin", NULL);
     
     
     
     // Execute the kernel
     clSetKernelArg(kernel, 0, sizeof(buffer), &buffer);
     size_t global_dimensions[] = {LENGTH,0,0};
     clEnqueueNDRangeKernel(queue, kernel, 1, NULL, global_dimensions, NULL, 0, NULL, NULL);
     
     
     
     // Read back the results
     clEnqueueReadBuffer(queue, buffer, CL_TRUE, 0, sizeof(cl_float)*LENGTH, data, 0, NULL, NULL);
     
     
     
     // Clean up
     clReleaseMemObject(buffer);
     clReleaseKernel(kernel);
     clReleaseProgram(program);
     clReleaseCommandQueue(queue);
     clReleaseContext(context);
     
     
     
     // Print out the results
     for (int i=0; i LENGTH; i++)
      printf("sin(%d) = %f\n", i, data[i]);
     
     
     
     free(data);
    }