cuda在乘法计数器中计算错误结果

时间:2014-07-12 17:06:50

标签: cuda

我正在用cuda编写代码来尝试学习一些概念,这就是问题所在:

在行 @@@ 如果我使用(i * i)它运行良好且乘法结果为真。但是当我把(i * j)计数器,而不是(i * i)时,它会产生错误的结果。我认为错误的 dimgrid& amp; dimblock 或其他东西!任何想法如何解决问题?
我把c ++版本放在我的代码末尾来比较结果。 谢谢你的建议。

这是我的代码:

#include "cuda.h"
#include "stdio.h"
#include "stdlib.h"
#include "iostream"
#include "time.h"

double diffclock(clock_t clock1,clock_t clock2) 
{
double diffticks=clock1-clock2;
double diffms=(diffticks*10)/CLOCKS_PER_SEC;
return diffms;
} 

using namespace std;
__global__ void add( int *c)
{

int i = threadIdx.x + blockIdx.x * blockDim.x;
int j = threadIdx.y + blockIdx.y * blockDim.y;
int k = threadIdx.z + blockIdx.z * blockDim.z;
int nx,ny,nz;
nx = 512;
ny = 512 ;
nz = 51200 ;
if ((i < nx) && (j < ny) && (k < nz))
{

    *c = i*i; // **@@@**

}
}

int main()
{
printf("****************************************************************\n");
printf("                  CUDA_C COMPARISONE MODEL                          \n");
printf("\n");
printf("\n");
printf("this program will produce 512 * 512 * 51,200 for loop iteration \n");
printf("you can compare time elapsed between c++ version & cuda version \n");
printf("\n");
printf("\n");

printf("\n");
printf("****************************************************************\n");
cudaEvent_t beginEvent;
cudaEvent_t endEvent;
cudaEventCreate( &beginEvent );
cudaEventCreate( &endEvent );
int c;
int *dev_c;
cudaMalloc((void**)&dev_c, sizeof(int));
dim3 dimgrid (16 , 16);
dim3 dimblock(32 , 32);
cudaEventRecord( beginEvent, 0 );
add<<<dimgrid,dimblock>>>(dev_c);
cudaMemcpy(&c, dev_c, sizeof(int), cudaMemcpyDeviceToHost);
cudaEventRecord( endEvent, 0 );
cudaEventSynchronize( endEvent );
float timeValue;
cudaEventElapsedTime( &timeValue, beginEvent, endEvent );
printf( "Time elapsed in G-p-u : %f  ms \n" ,timeValue );
printf("_____________________________________________________\n");
printf("G-p-u multiply computation is =====>>> %d\n", c);
printf("_____________________________________________________\n");


// c++  code :

int n1 = 512 ;
int n2 = 512 ;
int n3 = 51200;

clock_t begin=clock();

int cp , ii,jj,kk;
for(kk=0; kk<n3; kk++)
  for(ii=0; ii<n2; ii++)
    for(jj=0; jj<n1; jj++)
         cp = (ii)*(jj);

clock_t end=clock();
cout << "Time elapsed in C-p-u : " << double(diffclock(end,begin)) << " ms"<< endl;
printf("_____________________________________________________\n");
printf("_____________________________________________________\n");

printf("C-p-u multiply computation is =====>>> %d\n", cp);
cudaFree(dev_c);
return 0;
}

1 个答案:

答案 0 :(得分:2)

对于CPU和GPU,您正在运行许多计算。您正在将来自CPU的一个计算与来自GPU的一个计算进行比较。问题是,你没有比较相同的计算,所以当然你的结果是不同的。您将结果存储在一个位置,一个位于另一个位置之上。那不会奏效。 CPU上的计算顺序与GPU上的计算顺序不同。

将每个计算存储在一个单独的位置,就像我完成here一样。然后,当您比较结果时,您将能够比较相应的位置,然后您的结果将匹配。

相关问题