c++ - 使用 Thrust 循环优化 CUDA

标签 c++ for-loop cuda thrust

给定以下代码,使用 Thrust(CUDA 的 C++ 模板库)生成一种带有 CUDA 的代码字典:

thrust::device_vector<float> dCodes(codes->begin(), codes->end());
thrust::device_vector<int> dCounts(counts->begin(), counts->end());
thrust::device_vector<int> newCounts(counts->size());

for (int i = 0; i < dCodes.size(); i++) {
    float code = dCodes[i];
    int count = thrust::count(dCodes.begin(), dCodes.end(), code);

    newCounts[i] = dCounts[i] + count;

    //Had we already a count in one of the last runs?
    if (dCounts[i] > 0) {
        newCounts[i]--;
    }

    //Remove
    thrust::detail::normal_iterator<thrust::device_ptr<float> > newEnd = thrust::remove(dCodes.begin()+i+1, dCodes.end(), code);
    int dist = thrust::distance(dCodes.begin(), newEnd);
    dCodes.resize(dist);
    newCounts.resize(dist);
}

codes->resize(dCodes.size());
counts->resize(newCounts.size());

thrust::copy(dCodes.begin(), dCodes.end(), codes->begin());
thrust::copy(newCounts.begin(), newCounts.end(), counts->begin());

问题是,我通过使用 CUDA 视觉分析器注意到了 4 字节的多个拷贝。 IMO 这是由生成的

  1. 循环计数器i
  2. 浮点代码int countdist
  3. 每次访问i以及上面提到的变量

这似乎会减慢一切(连续复制 4 个字节并不有趣......)。

那么,我如何告诉推力,这些变量应在设备上处理?或者他们已经这样了?

使用 Throw::device_ptr 对我来说似乎还不够,因为我不确定 for 循环是在主机上还是在设备上运行(这也可能是缓慢的另一个原因)。

最佳答案

对于 i 的每次重复,大小、索引、代码等都必须从主机复制到设备。 根据你的程序的方式,你无能为力。 为了获得最佳结果,请考虑在设备上移动整个 i 循环,这样您就不会拥有主机到设备的拷贝。

信任对于某些事情来说非常有用,但是在涉及性能并且算法不太适合可用函数的情况下,您可能必须重写以获得最佳性能而不显式使用推力算法。

关于c++ - 使用 Thrust 循环优化 CUDA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2405214/

相关文章:

javascript - 对于语句和 img 问题

linux - 带有两个输入文件的两个 for 循环 Linux

c++ - 通过函数调用 C++ 中的线程更改对象属性

c++ - 将模板函数传递给模板函数

javascript - 谷歌应用程序脚本循环范围参数

python - 为 Pycuda 释放内存

c++ - cuda 内核未针对所有 blockIdx 执行

algorithm - 使用二进制搜索的并行合并排序

c++ - 使用 make_shared 时堆损坏

c++ - 没有双缓冲的 WM_EX_COMPOSITED