我正在尝试创建一个cuda程序,该程序通过归约算法计算长向量中的真值(由非零值定义)的数量。我得到了有趣的结果。我得到0或(ceil(N/threadsPerBlock)*threadsPerBlock),两者都不正确。
__global__ void count_reduce_logical(int * l, int * cntl, int N){
// suml is assumed to blockDim.x long and hold the partial counts
__shared__ int cache[threadsPerBlock];
int cidx = threadIdx.x;
int tid = threadIdx.x + blockIdx.x*blockDim.x;
int cnt_tmp=0;
while(tid<N){
if(l[tid]!=0)
cnt_tmp++;
tid+=blockDim.x*gridDim.x;
}
cache[cidx]=cnt_tmp;
__syncthreads();
//reduce
int k =blockDim.x/2;
while(k!=0){
if(threadIdx.x<k)
cache[cidx] += cache[cidx];
__syncthreads();
k/=2;
}
if(cidx==0)
cntl[blockIdx.x] = cache[0];
}然后,主机代码收集cntl结果并完成求和。这将是一个更大的项目的一部分,其中数据已经在GPU上,所以在那里进行计算是有意义的,如果它们工作正常的话。
发布于 2010-10-15 07:41:17
在你的缩减中,你正在做:
cache[cidx] += cache[cidx];难道您不想查看块的本地值的另一半吗?
发布于 2010-10-15 09:32:16
您可以使用Thrust在一行代码中执行count the nonzero-values。下面是计算device_vector中1的数量的代码片段。
#include <thrust/count.h>
#include <thrust/device_vector.h>
...
// put three 1s in a device_vector
thrust::device_vector<int> vec(5,0);
vec[1] = 1;
vec[3] = 1;
vec[4] = 1;
// count the 1s
int result = thrust::count(vec.begin(), vec.end(), 1);
// result == 3如果您的数据不在device_vector中,您仍然可以使用thrust::count by wrapping the raw pointers。
https://stackoverflow.com/questions/3938337
复制相似问题