Basic Arithmetic Operation in PyCuda

A basic functioning operation is carried out

If you like, you may put your contact info here.

License of this example:

Sugeerth Murugesan,UC Davis (sugeerth@gmail.com)

Date:

September 2nd,2013

PyCUDA version:

   1 #!python
   2 import pycuda.driver as cuda
   3 import pycuda.autoinit
   4 from pycuda.compiler import SourceModule
   5 import pycuda.gpuarray as gpuarray
   6 import numpy as np
   7 
   8 #Converting the list into numpy array for faster acess and putting it into the GPU for processing... 
   9 start = cuda.Event()
  10 end = cuda.Event()
  11 values = np.random.randn(222341)
  12 #self.Array_SIze is the size
  13 number_of_blocks=222341/1024
  14 
  15 #Calculating the (Value-max)/max-min computation and storing it in a numpy array. Pre-calculating the maximum and minimum values.
  16 
  17 # Space for the Kernel computation..
  18 
  19 func_mod = SourceModule("""
  20 // Needed to avoid name mangling so that PyCUDA can
  21 // find the kernel function:
  22 extern "C" {
  23 __global__ void func(float *a,int N,float minval,int denom)
  24 {
  25 int idx = threadIdx.x+threadIdx.y*32+blockIdx.x*blockDim.x;
  26 if (idx < N)
  27     a[idx] = (a[idx]-minval)/denom;
  28 }
  29 }
  30 """, no_extern_c=1)
  31 
  32 func = func_mod.get_function('func')
  33 N = 222341
  34 x = np.asarray(values, np.float32)
  35 x_gpu = gpuarray.to_gpu(x)
  36 h_minval = np.int32(0)
  37 h_denom=np.int32(255)
  38 
  39 start.record()
  40 # a function to the GPU to caluculate the computation in the GPU.
  41 func(x_gpu.gpudata, np.uint32(N),np.uint32(h_minval),np.uint32(h_denom),block=(1024, 1, 1),grid=(number_of_blocks+1,1,1))
  42 end.record() 
  43 end.synchronize()
  44 secs = start.time_till(end)*1e-3
  45 
  46 print "SourceModule time and first three results:"
  47 print "%fs, %s" % (secs, str(x[:3]))
  48 print 'x:       ', x[222341-1]
  49 print 'Func(x): ', x_gpu.get()[222341-1],'Actual: ',(values[222341-1]-0)/(h_denom)
  50 x_colors=x_gpu.get()

PyCuda/Examples/ArithmeticExample (last edited 2013-09-03 06:35:32 by 99-121-203-69)