Advertisement
Guest User

Untitled

a guest
Sep 6th, 2010
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 10.44 KB | None | 0 0
  1. //
  2. // File:       hello.c
  3. //
  4. // Abstract:   A simple "Hello World" compute example showing basic usage of OpenCL which
  5. //             calculates the mathematical square (X[i] = pow(X[i],2)) for a buffer of
  6. //             floating point values.
  7. //
  8. //
  9. // Version:    <1.0>
  10. //
  11. // Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Inc. ("Apple")
  12. //             in consideration of your agreement to the following terms, and your use,
  13. //             installation, modification or redistribution of this Apple software
  14. //             constitutes acceptance of these terms.  If you do not agree with these
  15. //             terms, please do not use, install, modify or redistribute this Apple
  16. //             software.
  17. //
  18. //             In consideration of your agreement to abide by the following terms, and
  19. //             subject to these terms, Apple grants you a personal, non - exclusive
  20. //             license, under Apple's copyrights in this original Apple software ( the
  21. //             "Apple Software" ), to use, reproduce, modify and redistribute the Apple
  22. //             Software, with or without modifications, in source and / or binary forms;
  23. //             provided that if you redistribute the Apple Software in its entirety and
  24. //             without modifications, you must retain this notice and the following text
  25. //             and disclaimers in all such redistributions of the Apple Software. Neither
  26. //             the name, trademarks, service marks or logos of Apple Inc. may be used to
  27. //             endorse or promote products derived from the Apple Software without specific
  28. //             prior written permission from Apple.  Except as expressly stated in this
  29. //             notice, no other rights or licenses, express or implied, are granted by
  30. //             Apple herein, including but not limited to any patent rights that may be
  31. //             infringed by your derivative works or by other works in which the Apple
  32. //             Software may be incorporated.
  33. //
  34. //             The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO
  35. //             WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
  36. //             WARRANTIES OF NON - INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A
  37. //             PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION
  38. //             ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
  39. //
  40. //             IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
  41. //             CONSEQUENTIAL DAMAGES ( INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  42. //             SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  43. //             INTERRUPTION ) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION
  44. //             AND / OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER
  45. //             UNDER THEORY OF CONTRACT, TORT ( INCLUDING NEGLIGENCE ), STRICT LIABILITY OR
  46. //             OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  47. //
  48. // Copyright ( C ) 2008 Apple Inc. All Rights Reserved.
  49. //
  50.  
  51. ////////////////////////////////////////////////////////////////////////////////
  52.  
  53. #include <fcntl.h>
  54. #include <stdio.h>
  55. #include <stdlib.h>
  56. #include <string.h>
  57. #include <math.h>
  58. #include <unistd.h>
  59. #include <sys/types.h>
  60. #include <sys/stat.h>
  61. #include <CL/cl.h>
  62.  
  63. ////////////////////////////////////////////////////////////////////////////////
  64.  
  65. // Use a static data size for simplicity
  66. //
  67. #define DATA_SIZE (65536)
  68.  
  69. ////////////////////////////////////////////////////////////////////////////////
  70.  
  71. // Simple compute kernel which computes the square of an input array
  72. //
  73. const char *KernelSource = "\n" \
  74. "__kernel void square(                                                       \n" \
  75. "   __global float* input,                                              \n" \
  76. "   __global float* output,                                             \n" \
  77. "   const unsigned int count)                                           \n" \
  78. "{                                                                      \n" \
  79. "   int i = get_global_id(0);                                           \n" \
  80. "   if(i < count)                                                       \n" \
  81. "       output[i] = input[i] * input[i];                                \n" \
  82. "}                                                                      \n" \
  83. "\n";
  84.  
  85. ////////////////////////////////////////////////////////////////////////////////
  86.  
  87. int main(int argc, char** argv)
  88. {
  89.     int err;                            // error code returned from api calls
  90.      
  91.     float data[DATA_SIZE];              // original data set given to device
  92.     float results[DATA_SIZE];           // results returned from device
  93.     unsigned int correct;               // number of correct results returned
  94.  
  95.     size_t global;                      // global domain size for our calculation
  96.     size_t local;                       // local domain size for our calculation
  97.  
  98.     cl_platform_id platform;
  99.     cl_device_id device_id;             // compute device id
  100.     cl_context context;                 // compute context
  101.     cl_command_queue commands;          // compute command queue
  102.     cl_program program;                 // compute program
  103.     cl_kernel kernel;                   // compute kernel
  104.    
  105.     cl_mem input;                       // device memory used for the input array
  106.     cl_mem output;                      // device memory used for the output array
  107.    
  108.     // Fill our data set with random float values
  109.     //
  110.     int i = 0;
  111.     unsigned int count = DATA_SIZE;
  112.     for(i = 0; i < count; i++)
  113.         data[i] = rand() / (float)RAND_MAX;
  114.        
  115.     // Get Platform IDs
  116.     err = clGetPlatformIDs(1, &platform, NULL);
  117.     if (err != CL_SUCCESS) {
  118.         printf("Error: Failed to query platforms! (%d)\n", err);
  119.         return EXIT_FAILURE;
  120.     }
  121.    
  122.     // Connect to a compute device
  123.     //
  124.     int gpu = 1;
  125.     err = clGetDeviceIDs(platform, gpu ? CL_DEVICE_TYPE_GPU : CL_DEVICE_TYPE_CPU, 1, &device_id, NULL);
  126.     if (err != CL_SUCCESS)
  127.     {
  128.         printf("Error: Failed to create a device group! (%d)\n", err);
  129.         return EXIT_FAILURE;
  130.     }
  131.  
  132.     // Create a compute context
  133.     //
  134.     context = clCreateContext(0, 1, &device_id, NULL, NULL, &err);
  135.     if (!context)
  136.     {
  137.         printf("Error: Failed to create a compute context! (%d)\n", err);
  138.         return EXIT_FAILURE;
  139.     }
  140.  
  141.     // Create a command commands
  142.     //
  143.     commands = clCreateCommandQueue(context, device_id, 0, &err);
  144.     if (!commands)
  145.     {
  146.         printf("Error: Failed to create a command commands!\n");
  147.         return EXIT_FAILURE;
  148.     }
  149.  
  150.     // Create the compute program from the source buffer
  151.     //
  152.     program = clCreateProgramWithSource(context, 1, (const char **) & KernelSource, NULL, &err);
  153.     if (!program)
  154.     {
  155.         printf("Error: Failed to create compute program!\n");
  156.         return EXIT_FAILURE;
  157.     }
  158.  
  159.     // Build the program executable
  160.     //
  161.     err = clBuildProgram(program, 0, NULL, NULL, NULL, NULL);
  162.     if (err != CL_SUCCESS)
  163.     {
  164.         size_t len;
  165.         char buffer[2048];
  166.  
  167.         printf("Error: Failed to build program executable!\n");
  168.         clGetProgramBuildInfo(program, device_id, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len);
  169.         printf("%s\n", buffer);
  170.         exit(1);
  171.     }
  172.  
  173.     // Create the compute kernel in the program we wish to run
  174.     //
  175.     kernel = clCreateKernel(program, "square", &err);
  176.     if (!kernel || err != CL_SUCCESS)
  177.     {
  178.         printf("Error: Failed to create compute kernel!\n");
  179.         exit(1);
  180.     }
  181.  
  182.     // Create the input and output arrays in device memory for our calculation
  183.     //
  184.     input = clCreateBuffer(context,  CL_MEM_READ_ONLY,  sizeof(float) * count, NULL, NULL);
  185.     output = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(float) * count, NULL, NULL);
  186.     if (!input || !output)
  187.     {
  188.         printf("Error: Failed to allocate device memory!\n");
  189.         exit(1);
  190.     }    
  191.    
  192.     // Write our data set into the input array in device memory
  193.     //
  194.     err = clEnqueueWriteBuffer(commands, input, CL_TRUE, 0, sizeof(float) * count, data, 0, NULL, NULL);
  195.     if (err != CL_SUCCESS)
  196.     {
  197.         printf("Error: Failed to write to source array!\n");
  198.         exit(1);
  199.     }
  200.  
  201.     // Set the arguments to our compute kernel
  202.     //
  203.     err = 0;
  204.     err  = clSetKernelArg(kernel, 0, sizeof(cl_mem), &input);
  205.     err |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &output);
  206.     err |= clSetKernelArg(kernel, 2, sizeof(unsigned int), &count);
  207.     if (err != CL_SUCCESS)
  208.     {
  209.         printf("Error: Failed to set kernel arguments! %d\n", err);
  210.         exit(1);
  211.     }
  212.  
  213.     // Get the maximum work group size for executing the kernel on the device
  214.     //
  215.     err = clGetKernelWorkGroupInfo(kernel, device_id, CL_KERNEL_WORK_GROUP_SIZE, sizeof(local), &local, NULL);
  216.     if (err != CL_SUCCESS)
  217.     {
  218.         printf("Error: Failed to retrieve kernel work group info! %d\n", err);
  219.         exit(1);
  220.     }
  221.  
  222.     // Execute the kernel over the entire range of our 1d input data set
  223.     // using the maximum number of work group items for this device
  224.     //
  225.     global = count;
  226.     err = clEnqueueNDRangeKernel(commands, kernel, 1, NULL, &global, &local, 0, NULL, NULL);
  227.     if (err)
  228.     {
  229.         printf("Error: Failed to execute kernel!\n");
  230.         return EXIT_FAILURE;
  231.     }
  232.  
  233.     // Wait for the command commands to get serviced before reading back results
  234.     //
  235.     clFinish(commands);
  236.  
  237.     // Read back the results from the device to verify the output
  238.     //
  239.     err = clEnqueueReadBuffer( commands, output, CL_TRUE, 0, sizeof(float) * count, results, 0, NULL, NULL );  
  240.     if (err != CL_SUCCESS)
  241.     {
  242.         printf("Error: Failed to read output array! %d\n", err);
  243.         exit(1);
  244.     }
  245.    
  246.     // Validate our results
  247.     //
  248.     correct = 0;
  249.     for(i = 0; i < count; i++)
  250.     {
  251.         if(results[i] == data[i] * data[i])
  252.             correct++;
  253.     }
  254.    
  255.     // Print a brief summary detailing the results
  256.     //
  257.     printf("Computed '%d/%d' correct values!\n", correct, count);
  258.    
  259.     // Shutdown and cleanup
  260.     //
  261.     clReleaseMemObject(input);
  262.     clReleaseMemObject(output);
  263.     clReleaseProgram(program);
  264.     clReleaseKernel(kernel);
  265.     clReleaseCommandQueue(commands);
  266.     clReleaseContext(context);
  267.  
  268.     return 0;
  269. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement