不使用 device_vectors 的 Cuda 推力?

标签 cuda thrust reduction

我使用普通 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/

相关文章:

c++ - CUDA矩阵乘法,执行时间长

c - 如何在 Cuda 中的简单 if 语句中避免分歧分支

cudaHostRegister 在计算能力为 1.1 的 GPU 上返回 cudaErrorInvalidValue

从全局函数调用设备函数

c++ - 使用 CUDA 的 Thrust 库进行数组缩减

cuda - 推力::device_vector错误

c++ - 表示嵌套的 C++ 模板

c - 为什么需要 OpenMP 减少子句来使减少并发?

algorithm - 归约概念中的一个非常复杂的问题

Java Stream.collect() lambda 参数类型