当前位置: 首页 > news >正文

Thrust库中的Gather和Scatter操作

Thrust库中的Gather和Scatter操作

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

Gather操作

Gather操作从一个源数组中按照指定的索引收集元素到目标数组中。

函数原型:

template<typename InputIterator1, typename InputIterator2, typename OutputIterator>
OutputIterator gather(InputIterator1 map_first, InputIterator1 map_last,InputIterator2 input_first, OutputIterator result);

工作方式:

result[i] = input[map[i]] 对于 map中的每个索引i

示例:

#include <thrust/gather.h>
#include <thrust/device_vector.h>// 源数据
thrust::device_vector<int> input(4);
input[0] = 10; input[1] = 20; input[2] = 30; input[3] = 40;// 索引映射
thrust::device_vector<int> map(3);
map[0] = 3; map[1] = 1; map[2] = 2;// 目标向量
thrust::device_vector<int> result(3);// 执行gather操作
thrust::gather(map.begin(), map.end(), input.begin(), result.begin());
// result现在包含 [40, 20, 30]

Scatter操作

Scatter操作将源数组的元素按照指定的索引分散到目标数组中。

函数原型:

template<typename InputIterator1, typename InputIterator2, typename InputIterator3, typename OutputIterator>
OutputIterator scatter(InputIterator1 first, InputIterator1 last,InputIterator2 map_first, InputIterator3 stencil,OutputIterator result);

工作方式:

result[map[i]] = input[i] 对于 map中的每个索引i

示例:

#include <thrust/scatter.h>
#include <thrust/device_vector.h>// 源数据
thrust::device_vector<int> input(3);
input[0] = 10; input[1] = 20; input[2] = 30;// 索引映射
thrust::device_vector<int> map(3);
map[0] = 3; map[1] = 1; map[2] = 2;// 目标向量(需要足够大)
thrust::device_vector<int> result(4);// 执行scatter操作
thrust::scatter(input.begin(), input.end(), map.begin(), result.begin());
// result现在包含 [0, 20, 30, 10] (初始值为0)

应用场景

  1. 数据重排:当需要按照特定顺序重新排列数据时
  2. 稀疏矩阵操作:在稀疏矩阵计算中高效地访问非零元素
  3. 数据库操作:实现类似SQL中的选择和投影操作
  4. 图像处理:像素重映射操作

变体函数

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

  • gather_if:带条件的gather操作
  • scatter_if:带条件的scatter操作
  • stable_scatter:保持相对顺序的scatter操作

这些操作在GPU上高度优化,能够充分利用并行计算能力,比在CPU上实现的类似操作要快得多。

相关文章:

  • 【Linux】第十六章 分析和存储日志
  • uniapp vue 沉浸式窗体如何获取并排除外部手机浏览器底部菜单栏工具栏高度
  • sqli—labs第六关——双引号报错注入
  • 小白学习java第18天(上):spring
  • 【C++】17. 多态
  • 大型企业数据治理与数据资产化:数字化转型的炼金术革命
  • 如何解决电脑蓝屏错误代码:Oxc0000098
  • 鸿蒙OSUniApp开发支持多语言的国际化组件#三方框架 #Uniapp
  • elementUI调整滚动条高度后与固定列冲突问题解决
  • 高海拔和远距离的人员识别:面部、体型和步态的融合
  • Java 源码 HashMap源码分析
  • PROE 转 STP 全攻略:软件实操、在线转换与问题解决
  • 【网工第6版】第10章 网络规划和设计②
  • D. Eating【Codeforces Round 1005 (Div. 2)】
  • 微机原理与接口技术知识点总结——8086微处理器ddddd
  • 16 - VDMA之视频转发实验
  • 字符串检索算法:KMP和Trie树
  • 解决 PicGo 上传 GitHub图床及Marp中Github图片编译常见难题指南
  • VUE3 -综合实践(Mock+Axios+ElementPlus)
  • 安全合规检查开源项目ComplianceAsCode/content详解及操作系统新产品开发适配指南
  • 男子不满和睦家医院手术效果还遇到了“冒牌医生”?院方回应
  • 从《让·桑特伊》到《追忆》,假故事的胜利
  • 崔登荣任国家游泳队总教练
  • 上海杨浦:鼓励龙头企业与高校共建创新联合体,最高支持200万元
  • 硅料收储挺价“小作文”发酵光伏板块罕见大涨,知情人士:确实在谈
  • 外交部:正确认识和对待历史是检验日本能否恪守和平发展承诺的重要标准