Skip to content

Instantly share code, notes, and snippets.

@velikodniy
Created December 11, 2015 10:17
Show Gist options
  • Save velikodniy/fb5ebbf35c3cb79c7fc7 to your computer and use it in GitHub Desktop.
Save velikodniy/fb5ebbf35c3cb79c7fc7 to your computer and use it in GitHub Desktop.
PyOpenCL example
import numpy as np
import pyopencl as cl
N = 1000000
a_np = np.random.rand(N).astype(np.float32)
b_np = np.random.rand(N).astype(np.float32)
ctx = cl.create_some_context(answers=['0'])
queue = cl.CommandQueue(ctx)
mf = cl.mem_flags
a_g = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=a_np)
b_g = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=b_np)
prg = cl.Program(ctx, """
__kernel void sum(__global const float *a_g, __global const float *b_g, __global float *res_g) {
int gid = get_global_id(0);
res_g[gid] = a_g[gid] + b_g[gid];
}
""").build()
res_g = cl.Buffer(ctx, mf.WRITE_ONLY, a_np.nbytes)
prg.sum(queue, a_np.shape, None, a_g, b_g, res_g)
res_np = np.empty_like(a_np)
cl.enqueue_copy(queue, res_np, res_g)
print(res_np - (a_np + b_np))
print(np.linalg.norm(res_np - (a_np + b_np)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment