Created
May 18, 2016 20:14
-
-
Save diegopso/e39ecd30bd86aaf11f6ce111aba443a5 to your computer and use it in GitHub Desktop.
First code with pyopencl
This file contains hidden or 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
import numpy | |
import pyopencl as cl | |
import os | |
#os.environ['PYOPENCL_COMPILER_OUTPUT'] = '1' | |
os.environ['PYOPENCL_CTX'] = '0:1' | |
N = 5 | |
# create host arrays | |
h_a = numpy.random.rand(N).astype(numpy.float32) | |
h_b = numpy.random.rand(N).astype(numpy.float32) | |
h_c = numpy.empty_like(h_a) | |
# create context, queue and program | |
context = cl.create_some_context() | |
queue = cl.CommandQueue(context) | |
kernelsource = open('vadd.cl').read() | |
program = cl.Program(context, kernelsource).build() | |
# create device buffers | |
mf = cl.mem_flags | |
d_a = cl.Buffer(context, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=h_a) | |
d_b = cl.Buffer(context, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=h_b) | |
d_c = cl.Buffer(context, mf.WRITE_ONLY, h_c.nbytes) | |
# run kernel | |
vadd = program.vadd | |
vadd.set_scalar_arg_dtypes([None, None, None, numpy.uint32]) | |
vadd(queue, h_a.shape, None, d_a, d_b, d_c, N) | |
# return results | |
cl.enqueue_copy(queue, h_c, d_c) | |
print(h_a) | |
print(h_b) | |
print(h_c) |
This file contains hidden or 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
__kernel void vadd(__global float *a, __global float *b, __global float *c, const unsigned int n) | |
{ | |
//Get our global thread ID | |
int id = get_global_id(0); | |
// Make sure we do not go out of bounds | |
if (id < n) { | |
c[id] = a[id] + b[id]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment