在Thrust中使用仿函数中的其他数据字段的最佳方法是什么?

时间:2015-06-10 07:08:22

标签: c++ cuda functor thrust

thrust算法thrust::transform等算法中使用的仿函数中使用某些常量数据的正确(或最佳)方法是什么?我使用的天真方式只是在仿函数的operator()方法中分配必需的数组,如下所示:

struct my_functor {

    __host__ __device__
    float operator()(thrust::tuple<float, float> args) {

        float A[2][10] = {
            { 4.0, 1.0, 8.0, 6.0, 3.0, 2.0, 5.0, 8.0, 6.0, 7.0 },
            { 4.0, 1.0, 8.0, 6.0, 7.0, 9.0, 5.0, 1.0, 2.0, 3.6 }};

        float x1 = thrust::get<0>(args);
        float x2 = thrust::get<1>(args);

        float result = 0.0;
        for (int i = 0; i < 10; ++i)
            result += x1 * A[0][i] + x2 * A[1][i];

        return result;
    }
}
但它似乎不是很优雅或有效的方式。现在我必须开发相对复杂的函子,其中包含一些矩阵(常量,如上例所示)以及函子operator()方法中使用的其他方法。解决此类问题的最佳方法是什么?感谢。

1 个答案:

答案 0 :(得分:2)

从你上一篇评论中可以清楚地看出,你在这里真正要问的是函子参数初始化。 CUDA使用C ++对象模型,因此结构具有类语义和行为。所以你的示例函子

struct my_functor {
    __host__ __device__
    float operator()(thrust::tuple<float, float> args) const {
        float A[2] = {50., 55.6};

        float x1 = thrust::get<0>(args);
        float x2 = thrust::get<1>(args);

        return x1 * A[0]+ x2 * A[1];
    }
}

可以使用带有初始化列表的空构造函数重写,以将仿函数中的硬编码常量转换为运行时可分配值:

struct my_functor {
    float A0, A1;

    __host__ __device__
    my_functor(float _a0, _a1) : A0(_a0), A1(_a1) { }

    __host__ __device__
    float operator()(thrust::tuple<float, float> args) const {
        float x1 = thrust::get<0>(args);
        float x2 = thrust::get<1>(args);

        return x1 * A0 + x2 * A1;
    }
}

您可以实例化多个版本的仿函数,每个仿函数具有不同的常量值,以便将您使用仿函数与推力库结合使用。

相关问题