LikeRampage

C++ OpenCL example

Oct 5th, 2021 (edited)
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.32 KB | None | 0 0
  1. // OpenCL Example.cpp : This file contains the 'main' function. Program execution begins and ends there.
  2. //
  3. /*Includes Header,lib get:https://www.mediafire.com/file/k8sgburdq9tfza4/AMD+APP+SDK.rar/file*/
  4. #include <iostream>
  5. // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
  6. //
  7. // A minimalist OpenCL program.
  8. #include <CL/cl.h>
  9. #include <stdio.h>
  10. #include <Windows.h>
  11.  
  12. #pragma comment(lib,"OpenCL.lib");
  13.  
  14. #define NWITEMS 512
  15. // A simple memset kernel
  16. const char* source =
  17. "__kernel void memset( __global uint *dst ) \n"
  18. "{ \n"
  19. " dst[get_global_id(0)] = get_global_id(0); \n"
  20. "} \n";
  21. int main(int argc, char** argv)
  22. {
  23.     // 1. Get a platform.
  24.     cl_platform_id platform;
  25.  
  26.     clGetPlatformIDs(1, &platform, NULL);
  27.     // 2. Find a gpu device.
  28.     cl_device_id device;
  29.  
  30.     clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU,
  31.         1,
  32.         &device,
  33.         NULL);
  34.     // 3. Create a context and command queue on that device.
  35.     cl_context context = clCreateContext(NULL,
  36.         1,
  37.         &device,
  38.         NULL, NULL, NULL);
  39.     cl_command_queue queue = clCreateCommandQueueWithProperties(context,
  40.         device,
  41.         0, NULL);
  42.     // 4. Perform runtime source compilation, and obtain kernel entry point.
  43.     cl_program program = clCreateProgramWithSource(context,
  44.         1,
  45.         &source,
  46.         NULL, NULL);
  47.     clBuildProgram(program, 1, &device, NULL, NULL, NULL);
  48.     cl_kernel kernel = clCreateKernel(program, "memset", NULL);
  49.     // 5. Create a data buffer.
  50.  
  51.     unsigned int buf_size[1024];
  52.     cl_mem buffer = clCreateBuffer(context,
  53.         CL_MEM_READ_WRITE,sizeof(buf_size),0,0);
  54.     // 6. Launch the kernel. Let OpenCL pick the local work size.
  55.     size_t global_work_size = NWITEMS;
  56.     clSetKernelArg(kernel, 0, sizeof(buffer), (void*)&buffer);
  57.     clEnqueueNDRangeKernel(queue,
  58.         kernel,
  59.         1,
  60.         NULL,
  61.         &global_work_size,
  62.         NULL, 0, NULL, NULL);
  63.     clFinish(queue);
  64.     // 7. Look at the results via synchronous buffer map.
  65.     cl_uint* ptr;
  66.     ptr = (cl_uint*)clEnqueueMapBuffer(queue,
  67.         buffer,
  68.         CL_TRUE,
  69.         CL_MAP_READ,
  70.         0,
  71.         NWITEMS * sizeof(cl_uint),
  72.         0, NULL, NULL, NULL);
  73.     int i;
  74.     for (i = 0; i < NWITEMS; i++)
  75.         printf("%d %d\n", i, ptr[i]);
  76.     return 0;
  77. }
  78.  
Add Comment
Please, Sign In to add comment