在Thrust中使用函数中附加数据字段的最佳方式是什么?
What is the optimal way to use additional data fields in functors in 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()
方法中使用的附加方法。解决这个问题的最佳方法是什么?谢谢。
从你最后的评论来看,很明显你在这里真正问的是函子参数初始化。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;
}
}
您可以实例化任意多个版本的函子,每个版本都有不同的常数值,以完成与thrust库一起使用函子的任何任务。
相关文章:
- 将结构字段的类型展开为可变模板参数
- 将位字段导出到数组
- 为了方便起见,我应该避免公开私有字段变量吗
- 当字段可以为null时,如何使用C++接口在Avro中写入数据
- 在java中读取c++字节的位字段
- 链接器找不到在虚拟类 c++ 中访问的静态字段的符号
- 私有字段对象与私有继承?
- 声明没有默认构造函数的字段
- C++内存模型和位字段的最大序列
- 声明为无效的变量或字段'...' Ardunio 编译器上的错误
- 如何在QByteArray中放置和检索位字段而不会感到痛苦?
- C++ win32 如何使密码字段可选并启用复制和粘贴?
- 如何通过UDP接收QByteArray并将其解析为位字段结构?
- 仅匹配集合中的某些字段
- 结构字段名称与 GDB 中的 STL 数组冲突
- 如何使用位字段将数据从二进制文件复制到结构中?
- 从CSV文件中提取每个条目字段的最佳方法是什么
- 修改Boost多索引项的非索引字段的最佳方法:modify vs mutable
- C# 与 C/C++:我是否需要手动对结构字段进行排序以获得最佳性能
- 在c++中设置较低层次私有字段的最佳实践