我试图正确测量并行和顺序执行的时间,但我有疑问,因为:
假设我们有以下代码:
//get the time
clock_t start,finish;
double totaltime;
start = clock();
double *d_A, *d_B, *d_X;
cudaMalloc((void**)&d_A, sizeof(double) * Width * Width);
cudaMalloc((void**)&d_B, sizeof(double) * Width);
cudaMalloc((void**)&d_X, sizeof(double) * Width);
cudaMemcpy(d_A, A, sizeof(double) * Width * Width, cudaMemcpyHostToDevice);
cudaMemcpy(d_B, B, sizeof(double) * Width, cudaMemcpyHostToDevice);
do_parallel_matmul<<<dimB, dimT>>>(d_A, d_B, d_X, Width);
cudaMemcpy(X, d_X, sizeof(double) * Width, cudaMemcpyDeviceToHost);
finish = clock();
totaltime=(double)(finish-start)/CLOCKS_PER_SEC;
printf("%f", totaltime);
这个时间比连续时间长得多,测量如下:
clock_t start,finish;
double totaltime;
start = clock();
do_seq_matmult();
finish = clock();
totaltime=(double)(finish-start)/CLOCKS_PER_SEC;
printf("%f", totaltime);
所以我不知道我是否应该只测量CUDA内核时间如下:
clock_t start,finish;
double totaltime;
start = clock();
do_parallel_matmul();
finish = clock();
totaltime=(double)(finish-start)/CLOCKS_PER_SEC;
printf("%f", totaltime);
并避免主机和设备之间的内存复制......
我之所以问上述问题,是因为我必须提交并行执行和顺序执行之间的比较...但是如果我在 CUDA 中测量内存副本,那么 CUDA 和 C 之间并没有很大的区别...
编辑:
void do_seq_matmult(const double *A, const double *X, double *resul, const int tam)
{
*resul = 0;
for(int i = 0; i < tam; i++)
{
for(int j = 0; j < tam; j++)
{
if(i != j)
*resul += A[i * tam + j] * X[j];
}
}
}
__global__ void do_parallel_matmul( double * mat_A,
double * vec,
double * rst,
int dim)
{
int rowIdx = threadIdx.x + blockIdx.x * blockDim.x; // Get the row Index
int aIdx;
while( rowIdx < dim)
{
rst[rowIdx] = 0; // clean the value at first
for (int i = 0; i < dim; i++)
{
aIdx = rowIdx * dim + i; // Get the index for the element a_{rowIdx, i}
rst[rowIdx] += (mat_A[aIdx] * vec[i] ); // do the multiplication
}
rowIdx += gridDim.x * blockDim.x;
}
__syncthreads();
}