Tutorial (original) (raw)
The hello world example gives a simple application that prints the name of the default compute device on the system.
The [boost::compute::system](../boost/compute/system.html "Class system") class provides access to the OpenCL platforms and devices present on the host system.
Compute devices are represented with the [device](../boost/compute/device.html "Class device") class.
#include
#include <boost/compute/core.hpp>
namespace compute = boost::compute;
int main() {
compute::device device = compute::system::default_device();
std::cout << "hello from " << device.name() << std::endl;
return 0;}
Before any computation occurs, data must be transferred from the host to the compute device. The generic [copy()](../boost/compute/copy.html "Function template copy") function provides a simple interface for transfering data and the generic[vector<T>](../boost/compute/vector.html "Class template vector") class provides a container for storing data on a compute device.
The following example shows how to transfer data from an array on the host to a [vector<T>](../boost/compute/vector.html "Class template vector") on the device and then back to a separate std::vector<T> on the host. At the end of the example both host_array and host_vector contain the same values which were copied through the memory on the compute device.
#include
#include <boost/compute/algorithm/copy.hpp> #include <boost/compute/container/vector.hpp>
namespace compute = boost::compute;
int main() {
compute::device device = compute::system::default_device();
compute::context context(device);
compute::command_queue queue(context, device);
int host_data[] = { 1, 3, 5, 7, 9 };
compute::vector<int> device_vector(5, context);
compute::copy(
host_data, host_data + 5, device_vector.begin(), queue
);
std::vector<int> host_vector(5);
compute::copy(
device_vector.begin(), device_vector.end(), host_vector.begin(), queue
);
return 0;}
The following example shows how to calculate the square-root of a vector of floats on a compute device using the [transform()](../boost/compute/transform.html "Function transform") function.
#include #include
#include <boost/compute/algorithm/transform.hpp> #include <boost/compute/container/vector.hpp> #include <boost/compute/functional/math.hpp>
namespace compute = boost::compute;
int main() {
compute::device device = compute::system::default_device();
compute::context context(device);
compute::command_queue queue(context, device);
std::vector<float> host_vector(10000);
std::generate(host_vector.begin(), host_vector.end(), rand);
compute::vector<float> device_vector(host_vector.size(), context);
compute::copy(
host_vector.begin(), host_vector.end(), device_vector.begin(), queue
);
compute::transform(
device_vector.begin(),
device_vector.end(),
device_vector.begin(),
compute::sqrt<float>(),
queue
);
compute::copy(
device_vector.begin(), device_vector.end(), host_vector.begin(), queue
);
return 0;}