pycuda int型变量传递

使用pycuda进行GPU编程时,参数转换与传递是必不可少的一步。通常在进行数组传递时,可以用一般方法进行内存分配并转换,例如:

import numpy
a = numpy.random.randn(4,4)
a = a.astype(numpy.float32)
a_gpu = cuda.mem_alloc(a.nbytes)
cuda.memcpy_htod(a_gpu, a)

通过以上步骤即可实现数组传递,唯一需要注意的是变量类型要先转换为float32这一cuda最方便处理的类型。
而除了数组之外,有时还需传递int型变量,此时如果还按上边的方法:

a=1
a_gpu = cuda.mem_alloc(a.nbytes)

会报错:AttributeError: ‘int’ object has no attribute ‘nbytes’
此时需要进行的正确操作是:

a=np.int32(a)

这样得到的a即可直接传入cuda核函数,无需其他操作。

猜你喜欢

转载自blog.csdn.net/qq_38402294/article/details/88625256
今日推荐