Here, we consider the task of adding two integer vectors again:
- Start importing the relevant libraries:
import pyopencl as cl
import pyopencl.array as cl_array
import numpy as np
- Define the context element (context) and the command queue (queue) :
context = cl.create_some_context()
queue = cl.CommandQueue(context)
- Here, we set the vector dimension and the space allocation for the input and output vectors:
vector_dim = 100 vector_a=cl_array.to_device(queue,np.random.randint(100,
size=vector_dim)) vector_b = cl_array.to_device(queue,np.random.randint(100,
size=vector_dim)) result_vector = cl_array.empty_like(vector_a)
- We set elementwiseSum as the application of ElementwiseKernel, and then set it to a set of arguments that define the operations to be applied to the input vectors:
elementwiseSum = cl.elementwise.ElementwiseKernel(context, "int *a,
int *b, int *c", "c[i] = a[i] + b[i]", "sum")
elementwiseSum(vector_a, vector_b, result_vector)
- Finally, we print the result:
print ("PyOpenCL ELEMENTWISE SUM OF TWO VECTORS")
print ("VECTOR LENGTH = %s" %vector_dimension)
print ("INPUT VECTOR A")
print (vector_a)
print ("INPUT VECTOR B")
print (vector_b)
print ("OUTPUT VECTOR RESULT A + B ")
print (result_vector)