Thrust库中的Gather和Scatter操纵

[复制链接]
发表于 2025-9-1 02:11:16 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
Thrust库中的Gather和Scatter操纵

Thrust是CUDA提供的一个类似于C++ STL的并行算法库,其中包含两个紧张的数据操纵:gather(聚集)和scatter(散开)。
Gather操纵

Gather操纵从一个源数组中按照指定的索引收集元素到目标数组中。
函数原型:
  1. template<typename InputIterator1, typename InputIterator2, typename OutputIterator>
  2. OutputIterator gather(InputIterator1 map_first,
  3.                      InputIterator1 map_last,
  4.                      InputIterator2 input_first,
  5.                      OutputIterator result);
复制代码
工作方式:
  1. result[i] = input[map[i]] 对于 map中的每个索引i
复制代码
示例:
  1. #include <thrust/gather.h>
  2. #include <thrust/device_vector.h>
  3. // 源数据
  4. thrust::device_vector<int> input(4);
  5. input[0] = 10; input[1] = 20; input[2] = 30; input[3] = 40;
  6. // 索引映射
  7. thrust::device_vector<int> map(3);
  8. map[0] = 3; map[1] = 1; map[2] = 2;
  9. // 目标向量
  10. thrust::device_vector<int> result(3);
  11. // 执行gather操作
  12. thrust::gather(map.begin(), map.end(), input.begin(), result.begin());
  13. // result现在包含 [40, 20, 30]
复制代码
Scatter操纵

Scatter操纵将源数组的元素按照指定的索引分散到目标数组中。
函数原型:
  1. template<typename InputIterator1, typename InputIterator2, typename InputIterator3, typename OutputIterator>
  2. OutputIterator scatter(InputIterator1 first,
  3.                       InputIterator1 last,
  4.                       InputIterator2 map_first,
  5.                       InputIterator3 stencil,
  6.                       OutputIterator result);
复制代码
工作方式:
  1. result[map[i]] = input[i] 对于 map中的每个索引i
复制代码
示例:
  1. #include <thrust/scatter.h>
  2. #include <thrust/device_vector.h>
  3. // 源数据
  4. thrust::device_vector<int> input(3);
  5. input[0] = 10; input[1] = 20; input[2] = 30;
  6. // 索引映射
  7. thrust::device_vector<int> map(3);
  8. map[0] = 3; map[1] = 1; map[2] = 2;
  9. // 目标向量(需要足够大)
  10. thrust::device_vector<int> result(4);
  11. // 执行scatter操作
  12. thrust::scatter(input.begin(), input.end(), map.begin(), result.begin());
  13. // result现在包含 [0, 20, 30, 10] (初始值为0)
复制代码
应用场景


  • 数据重排:当需要按照特定次序重新排列数据时
  • 稀疏矩阵操纵:在稀疏矩阵盘算中高效地访问非零元素
  • 数据库操纵:实现类似SQL中的选择和投影操纵
  • 图像处置惩罚:像素重映射操纵
变体函数

Thrust还提供了一些变体函数:

  • gather_if:带条件的gather操纵
  • scatter_if:带条件的scatter操纵
  • stable_scatter:保持相对次序的scatter操纵
这些操纵在GPU上高度优化,可以或许充实利用并行盘算能力,比在CPU上实现的类似操纵要快得多。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告
回复

使用道具 举报

×
登录参与点评抽奖,加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表