2017-04-21 41 views
0

我剛剛開始使用pyopencl模塊查看python中的OpenCl。在內核中使用OpenCl全局ID作爲整數

我有興趣生成沒有任何輸入的東西,例如生成正弦波的樣本。

要做到這一點,我需要的只是全局ID來進行計算,但是返回全局ID會導致一些奇特的數字。我用下面的代碼:

import numpy as np 
import pyopencl as cl 

Size = Width*Height 

# Get platforms, both CPU and GPU 
plat = cl.get_platforms() 
GPU = plat[0].get_devices() 

#Create context for GPU 
ctx = cl.Context(GPU) 

# Create queue for each kernel execution 
queue = cl.CommandQueue(ctx) 

mf = cl.mem_flags 

# Kernel function 
src = ''' 
__kernel void shader(__global float *result, __global int *width){ 

int w = *width; 
size_t gid = get_global_id(0); 

result[gid] = gid; 
} 
''' 

#Kernel function instantiation 
prg = cl.Program(ctx, src).build() 

#Allocate memory for variables on the device 
width_g = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=np.int32(Width)) 
result_g = cl.Buffer(ctx, mf.WRITE_ONLY, Size*8) 

# Call Kernel. Automatically takes care of block/grid distribution 
prg.shader(queue, (Size,), None , result_g, width_g) 
result = np.empty((Size,)) 
cl.enqueue_copy(queue, result, result_g) 

Image = result 

我要做的是全球ID複製到緩衝區對象result_d,但是當我檢查結果,我得到一些數字,甚至不是整數。我也嘗試將緩衝區設置爲整數而不是浮點數,但結果仍然相同。

我在做什麼錯?

回答

2

的問題是,在OpenCL的內核resultfloat類型的並在主機側的resultdouble類型。

指定主機緩衝器是float來解決這個問題:

result = np.empty((Size,),dtype=np.float32)