似乎在创建新的推力矢量所有元素默认为0时 - 我只是想确认这种情况总是如此。
如果是这样,是否有办法绕过构造函数负责此行为以获得额外的速度(因为对于某些向量我不需要它们具有初始值,例如如果他们的原始指针作为输出传递给CUBLAS)?
答案 0 :(得分:7)
thrust::device_vector
使用其提供的分配器构造它包含的元素,就像std::vector
一样。当向量要求分配器构造元素时,可以控制分配器的作用。
使用自定义分配器来避免向量元素的默认初始化:
// uninitialized_allocator is an allocator which
// derives from device_allocator and which has a
// no-op construct member function
template<typename T>
struct uninitialized_allocator
: thrust::device_malloc_allocator<T>
{
// note that construct is annotated as
// a __host__ __device__ function
__host__ __device__
void construct(T *p)
{
// no-op
}
};
// to make a device_vector which does not initialize its elements,
// use uninitialized_allocator as the 2nd template parameter
typedef thrust::device_vector<float, uninitialized_allocator<float> > uninitialized_vector;
你仍然需要花费内核启动来调用uninitialized_allocator::construct
,但是这个内核将是一个快速退出的no-op。你真正感兴趣的是避免填充阵列所需的内存带宽,这个解决方案就是这样做的。
有一个完整的示例代码here。
请注意,此技术需要Thrust 1.7或更高版本。