gpt4 book ai didi

c - 如何避免 thrust::device_vector 中元素的默认构造?

转载 作者:太空狗 更新时间:2023-10-29 17:02:33 25 4
gpt4 key购买 nike

  1. 似乎在创建新的推力 vector 时默认情况下所有元素都为 0 - 我只是想确认情况总是如此。

  2. 如果是这样,是否还有一种方法可以绕过负责此行为的构造函数以提高速度(因为对于某些 vector 我不需要它们具有初始值,例如如果它们的原始指针作为输出传递给 CUBLAS)?

最佳答案

thrust::device_vector 使用其提供的分配器构造它包含的元素,就像 std::vector 一样。当 vector 要求它构造一个元素时,可以控制分配器做什么。

使用自定义分配器来避免 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 的成本,但该内核将是空操作,很快就会退出。您真正感兴趣的是避免填充阵列所需的内存带宽,而此解决方案正是这样做的。

有一个完整的示例代码here .

请注意,此技术需要 Thrust 1.7 或更高版本。

关于c - 如何避免 thrust::device_vector 中元素的默认构造?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16389662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com