我使用普通 CUDA 代码编写了内核,该代码不使用推力设备向量。内核输出存储在设备上的数组中的一些结果,例如数组 X。我现在想对 X 进行归约。有没有一种方法可以使用推力::归约函数,而无需先将 X 复制到推力::device_vector 变量?
最佳答案
传统的方法是将设备指针包装到 thrust::device_ptr
中并将其传递给推力算法。 Thrust 中基于标签的模板模型将确保设备执行结果,因为调用中提供的输入序列的类型。
#include <thrust/device_ptr.h>
#include <thrust/reduce.h>
int* X;
cudaMalloc((void **)&X, sizeof(int) * size_t(N));
// Do stuff with X
thrust::device_ptr X_ptr(X);
int result = thrust::reduce(X_ptr, X_ptr+N);
从 Thrust 1.7 开始,引入了执行策略的概念。这样就无需使用 device_ptr
显式包装设备地址。因此,您可以使用 thrust::device
策略来指示输入迭代器位于设备上并执行类似的操作
#include <thrust/reduce.h>
#include <thrust/execution_policy.h>
int* X;
cudaMalloc((void **)&X, sizeof(int) * size_t(N));
// Do stuff with X
int result = thrust::reduce(thrust::device, X, X+N);
您选择哪种方式执行此操作应以您拥有的 Thrust 版本以及您喜欢的代码风格为指导。
关于不使用 device_vectors 的 Cuda 推力?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37095883/