Thrust快速入门教程(三) —— Algorithms

  Thrust提供了丰富的常用并行算法。这算法的功能与STL中的非常相似,于是我们使用了相同的名称(例如thrust::sortstd::sort)。

  所有的Thrust算法均提供了host端(主机端)和device端(设备端)的实现。当传入迭代器指向主机端时,将会调用主机端方法,当使用迭代器指向设备端时将调用设备端实现。

  在Thrust的算法中,的迭代器参数指向必须在同一存储位置,或者主机端或者设备端。除了thrust::copy,它可以任意的拷贝主机端和设备端的数据。


Transformations

  Transformations会对指定输入范围内的元素进行特定操作,并将其结果存储到指定位置。如thrust::fill

thrust::fill(D.begin(), D.begin() + 7, 9); // 将vector D的前7个元素设置为9

  此外transformations还包括thrust::sequencethrust::replacethrust::transform(衍生于C++的for_each)。完整的列表请参考文档

  下面的代码演示了几个transformation的用法。其中thrust::negatethrust::modulus与C++中的仿函数定义是一样的。Thrust在thrust/functional.h中也提供常用的仿函数,如plusmultiplies等。

#include <thrust/device_vector.h>
#include <thrust/transform.h>
#include <thrust/sequence.h>
#include <thrust/copy.h>
#include <thrust/fill.h>
#include <thrust/replace.h>
#include <thrust/functional.h>
#include <iostream>

int main(void)
{
  // allocate three device_vectors with 10 elements
  thrust::device_vector<int> X(10);
  thrust::device_vector<int> Y(10);
  thrust::device_vector<int> Z(10);

  // initialize X to 0,1,2,3, ....
  thrust::sequence(X.begin(), X.end());
  // compute Y = -X
  thrust::transform(X.begin(), X.end(), Y.begin(), thrust::negate<int>());
  // fill Z with twos
  thrust::fill(Z.begin(), Z.end(), 2);
  // compute Y = X mod 2
  thrust::transform(X.begin(), X.end(), Z.begin(), Y.
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值