Created
May 22, 2015 09:03
-
-
Save cckwes/16c26dd1ca50a39fd58a to your computer and use it in GitHub Desktop.
OpenCL example C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <CL/cl.hpp> | |
#include <QVector> | |
int main() | |
{ | |
std::vector<cl::Platform> all_platforms; | |
cl::Platform::get(&all_platforms); | |
if (all_platforms.empty()) | |
{ | |
std::cout << "No platform found" << std::endl; | |
exit(1); | |
} | |
cl::Platform default_platform = all_platforms[0]; | |
std::cout << "Using platform: " << default_platform.getInfo<CL_PLATFORM_NAME>() << std::endl; | |
std::vector<cl::Device> all_devices; | |
default_platform.getDevices(CL_DEVICE_TYPE_ALL, &all_devices); | |
if (all_devices.empty()) | |
{ | |
std::cout << "No device found" << std::endl; | |
exit(1); | |
} | |
cl::Device default_device = all_devices[0]; | |
std::cout << "Using device: " << default_device.getInfo<CL_DEVICE_NAME>() << std::endl; | |
cl::Context context({default_device}); | |
cl::Program::Sources sources; | |
std::string kernel_code = "void kernel simple_add(global const int *A, global int *B) {" | |
" B[get_global_id(0)] = A[get_global_id(0)] * 3;" | |
"}"; | |
sources.push_back({kernel_code.c_str(), kernel_code.length()}); | |
cl::Program program(context, sources); | |
if (program.build({default_device}) != CL_SUCCESS) | |
{ | |
std::cout << "Error building: " << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(default_device) << std::endl; | |
exit(1); | |
} | |
cl::Buffer buffer_A(context, CL_MEM_READ_WRITE, sizeof(int) * 10); | |
cl::Buffer buffer_B(context, CL_MEM_READ_WRITE, sizeof(int) * 10); | |
//change the array to vector | |
QVector<int> A; | |
for (int i = 0; i < 10; ++i) | |
A.push_back(i); | |
cl::CommandQueue queue(context, default_device); | |
queue.enqueueWriteBuffer(buffer_A, CL_TRUE, 0, sizeof(int) * 10, A.data()); | |
cl::Kernel kernel_add(program, "simple_add"); | |
kernel_add.setArg(0, buffer_A); | |
kernel_add.setArg(1, buffer_B); | |
queue.enqueueNDRangeKernel(kernel_add, cl::NullRange, cl::NDRange(10), cl::NullRange); | |
queue.finish(); | |
//change the array to vector | |
QVector<int> C; | |
C.resize(A.size()); | |
queue.enqueueReadBuffer(buffer_B, CL_TRUE, 0, sizeof(int)*10, C.data()); | |
std::cout << "Results: " << std::endl; | |
for (int i = 0; i < 10; ++i) | |
{ | |
std::cout << C[i] << "\t"; | |
} | |
std::cout << std::endl; | |
exit(0); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment