【发布时间】:2016-07-18 21:40:26
【问题描述】:
有没有一种方法可以自动将 CUDA 数学函数包装在仿函数中,这样就可以应用 thrust::transform 而无需手动编写仿函数?类似于(我收集的)std::function 提供的功能?
thrust::placeholders 似乎不喜欢数学函数。
std::function 似乎不可用。
示例代码:
#include <thrust/transform.h>
#include <thrust/device_vector.h>
#include <iostream>
#include <functional>
#include <math.h>
struct myfunc{
__device__
double operator()(double x,double y){
return hypot(x,y);
}
};
int main(){
double x0[10] = {3.,0.,1.,2.,3.,4.,5.,6.,7.,8.};
double y0[10] = {4.,0.,1.,2.,3.,4.,5.,6.,7.,8.};
thrust::device_vector<double> x(x0,x0+10);
thrust::device_vector<double> y(y0,y0+10);
thrust::device_vector<double> r(10);
for (int i=0;i<10;i++) std::cout << x0[i] <<" "; std::cout<<std::endl;
for (int i=0;i<10;i++) std::cout << y0[i] <<" "; std::cout<<std::endl;
// this works:
thrust::transform(x.begin(),x.end(),y.begin(),r.begin(), myfunc());
// this doesn't compile:
using namespace thrust::placeholders;
thrust::transform(x.begin(),x.end(),y.begin(),r.begin(), hypot(_1,_2));
// nor does this:
thrust::transform(x.begin(),x.end(),y.begin(),r.begin(), std::function<double(double,double)>(hypot));
for (int i=0;i<10;i++) std::cout << r[i] <<" "; std::cout<<std::endl;
}
【问题讨论】:
-
没有自动的方法来做到这一点。实现这样的事情的一种方法可能是制作类似
std::bindthat interoperated with CUDA的东西。然后你需要根据bind定义所有感兴趣的数学函数的重载(例如hypot)。 -
在 CUDA 7.5 中,您可以使用 experimental
--expt-extended-lambdafeature 并写入auto h = [] __device__(double x, double y){return hypot(x,y);}; thrust::transform(x.begin(),x.end(),y.begin(),r.begin(), h); -
@m.s.如果您想提供答案,我会赞成。我认为 Jared 不会反对。
标签: lambda cuda placeholder functor thrust