Sha*_* RC 4 c++ cuda vector thrust
我正在使用推力进行项目,它似乎缺少一些基本功能: -
在c ++中,将向量乘以常量的最简单方法是使用std::transform,std::bind1st如下所示:
std::transform(vec.begin(), vec.end(), vec.begin(),
std::bind1st(std::multiplies<double>(),myConst));
Run Code Online (Sandbox Code Playgroud)
但显然bind1st并bind2nd不能与推力工作.
那么,是否有一种简单的方法可以将矢量乘以推力常数?
PS:目前我正在使用我自己的仿函数来进行乘法运算:
thrust::for_each(vec.begin(), vec.end(), multiplyByConstant<double>(myConst))
Run Code Online (Sandbox Code Playgroud)
哪里
template< typename T >
struct multiplyByConstant
{
const T constant;
multiplyByConstant(T _constant) : constant(_constant) {}
__host__ __device__
void operator()( T& VecElem) const
{
VecElem=VecElem*constant;
}
};
Run Code Online (Sandbox Code Playgroud)
但是编写一个仿函数进行简单的乘法似乎有些过分.肯定必须有一个更简单的方法.
推力可以由具有适配器的工作,但是std::bind1st,std::bind2nd,std:bind不能使用.您将需要编写自己的__device__适配器功能(有关更多信息,请参见此处).
但是,推力1.7(应该在CUDA 5.5和更新版本中可用)支持lambda表达式,所以你的例子可以写成:
#include <thrust/functional.h>
#include <thrust/transform.h>
using namespace thrust::placeholders;
thrust::transform(vec.begin(), vec.end(), vec.begin(), myConst * _1);
Run Code Online (Sandbox Code Playgroud)
{免责声明,用浏览器编写,未经测试,使用风险自负}
如果您使用较旧的CUDA版本,那么您将无法定义仿函数.
一种简单的实现方法是使用Thrust的精美迭代器,该迭代器通常使您可以避免定义(尽可能多)函子。除了使用std :: bind1st从二进制函数中实现一元函数,您还可以将二进制函数与复杂的迭代器结合使用:
#include <thrust/transform.h>
#include <thrust/iterator/constant_iterator.h>
#include <thrust/functional.h>
...
thrust::transform(vec.begin(), vec.end(),
thrust::make_constant_iterator(myConst),
vec.begin(),
thrust::multiplies<int>());
Run Code Online (Sandbox Code Playgroud)
在我看来,该解决方案比使用std :: bind或lambda更为优雅。
花式迭代器的文档可以在这里找到。
| 归档时间: |
|
| 查看次数: |
2059 次 |
| 最近记录: |