您好我正在尝试编写CUDA内核来执行以下代码.
for (n = 0; n < (total-1); n++)
{
a = values[n];
for ( i = n+1; i < total ; i++)
{
b = values[i] - a;
c = b*b;
if( c < 10)
newvalues[i] = c;
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我目前所拥有的,但它似乎没有给出正确的结果?有谁知道我做错了什么.干杯
__global__ void calc(int total, float *values, float *newvalues){
float a,b,c;
int idx = blockIdx.x * blockDim.x + threadIdx.x;
for (int n = idx; n < (total-1); n += blockDim.x*gridDim.x){
a = values[n];
for(int i = n+1; i < total; i++){
b = values[i] - a;
c = b*b;
if( c < 10)
newvalues[i] = c;
}
}
Run Code Online (Sandbox Code Playgroud)
jwd*_*msd 11
在2D中实现此问题并使用2D线程块启动内核.x和y维度中的线程总数将等于total.内核代码应该如下所示:
__global__ void calc(float *values, float *newvalues, int total){
float a,b,c;
int n= blockIdy.y * blockDim.y + threadIdx.y;
int i= blockIdx.x * blockDim.x + threadIdx.x;
if (n>=total || i>=total)
return;
a = values[n];
b = values[i] - a;
c = b*b;
if( c < 10)
newvalues[i] = c;
// I don't know your problem statement but i think it should be like: newvalues[n*total+i] = c;
}
Run Code Online (Sandbox Code Playgroud)
更新:
这是你应该如何调用内核
dim3 block(16,16);
dim3 grid ( (total+15)/16, (total+15)/16 );
calc<<<grid,block>>>(float *val, float *newval, int T);
Run Code Online (Sandbox Code Playgroud)
还要确保在内核中添加此行(请参阅更新的内核)
if (n>=total || i>=total)
return;
Run Code Online (Sandbox Code Playgroud)