How to do it...

Here, we consider the task of adding two integer vectors again:

  1. Start importing the relevant libraries:
import pyopencl as cl
import pyopencl.array as cl_array
import numpy as np
  1. Define the context element (context) and the command queue (queue:
context = cl.create_some_context()
queue = cl.CommandQueue(context)
  1. 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)
  1. 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)
  1. 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)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset