马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
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)
复制代码 应用场景
- 数据重排:当需要按照特定次序重新排列数据时
- 稀疏矩阵操纵:在稀疏矩阵盘算中高效地访问非零元素
- 数据库操纵:实现类似SQL中的选择和投影操纵
- 图像处置惩罚:像素重映射操纵
变体函数
Thrust还提供了一些变体函数:
- gather_if:带条件的gather操纵
- scatter_if:带条件的scatter操纵
- stable_scatter:保持相对次序的scatter操纵
这些操纵在GPU上高度优化,可以或许充实利用并行盘算能力,比在CPU上实现的类似操纵要快得多。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
|