Skip to content

Instantly share code, notes, and snippets.

@mprymek
Last active July 18, 2019 14:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mprymek/8ca298f0ff2b139b0c63 to your computer and use it in GitHub Desktop.
Save mprymek/8ca298f0ff2b139b0c63 to your computer and use it in GitHub Desktop.
OpenCL in R example
# OpenCL in R example
#
# Kernel "gpu.sum" sums two vectors.
#
# Please note that in R OpenCL library:
#
# 1. the first argument must be the output vector
# 2. the second argument must be the length of the output
# 3. you must convert the input vectors to the right type ("as.double" here)
#
# (see ?oclRun)
library(OpenCL)
p = oclPlatforms()
d = oclDevices(p[[1]])
code <- c("
#pragma OPENCL EXTENSION cl_khr_fp64 : enable
__kernel void gpu_sum(
// first two args are mandatory
__global double* output,
const unsigned int n,
// user args
__global const double* input1,
__global const double* input2
)
{
int i = get_global_id(0);
if (i<n) output[i] = input1[i] + input2[i];
};
")
k.gpu.sum <- oclSimpleKernel(d[[1]], "gpu_sum", code, "double")
vector1 <- as.double(1:10)
vector2 <- as.double(2:11)
result <- oclRun(k.gpu.sum, length(vector1), vector1, vector2)
print(result)
# Output:
#
# > source('opencl-test.R')
# [1] 3 5 7 9 11 13 15 17 19 21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment