这是我的代码:
//initialize the device_vector
int size = N;
thrust::device_vector<glm::vec3> value(size);
thrust::device_vector<int> key(size);
//get the device pointer of the device_vector
//so than I can write data to the device_vector in CUDA kernel
glm::vec3 * dv_value_ptr = thrust::raw_pointer_cast(&value[0]);
int* dv_key_ptr = thrust::raw_pointer_cast(&key[0]);
//run the kernel function
dim3 threads(16, 16);
dim3 blocks(iDivUp(m_width, threads.x), iDivUp(m_height, threads.y));
//the size of value and key is packed in dev_data
compute_one_i_all_j <<<blocks, threads >>>(dev_data, dv_key_ptr, dv_value_ptr);
//Finally, reduce the vector by its keys.
thrust::pair<thrust::device_vector<int>::iterator,
thrust::device_vector<glm::vec3>::iterator> new_last;
new_last = thrust::reduce_by_key(key.begin(), key.end(), value.begin(), output_key.begin(), output_value.begin());
//get the reduced vector size
int new__size = new_last.first - output_key.begin();
完成所有这些代码后,我将
output_key
写入文件。我在文件中得到很多重复的键,如下所示:
所以,
reduce_by_key()
似乎不起作用。key
s和value
s,所以在内核之后key
和value
中的一些元素保持不变(可能是0)。
如文档中所述:
对于
范围内的每组连续键,[keys_first, keys_last)
将组的第一个元素复制到 keys_output。使用加号减少范围内的相应值,并将结果复制到 values_output。reduce_by_key
每组相等的连续键会减少
所以首先你必须重新排列所有的键和值,这样所有具有相同键的元素都是相邻的。最简单的方法是使用
sort_by_key
.
thrust::sort_by_key(key.begin(), key.end(), value.begin())
new_last = thrust::reduce_by_key(key.begin(), key.end(), value.begin(), output_key.begin(), output_value.begin());