大家好。
我写了个两个向量相加的程序。
N= 33*1024.
c=a+b
我将a,b传入到gpu中,用gpu相加,再传回来。
我现在想比较用cpu和gpu的计算时间(在程序中有标识出)。但不知道应该用什么函数。或是如何实现。
谢谢大家。
p.s. 论坛的搜索功能在哪。我没有找到。自己动手一个个的翻帖子似乎搞不定。
更新:2013年 10月 25日 星期五 18:10:16 CST 使用cudaEvent 相关的函数实现。主程序实现如下。
主程序如下
# include <stdio.h>
// include predef.h , define N
# include "predef.h"
// include the gpu fun, for easy debug
# include "fun_gpu_add_blockthread.h"
// main function
int main(void)
{
int a[N], b[N], c[N], host_c[N];
int *dev_a, *dev_b, *dev_c;
// 4 count gpu time ////////////////////
cudaEvent_t start_gpu,stop_gpu;
cudaEventCreate(&start_gpu);
cudaEventCreate(&stop_gpu);
cudaEventRecord(start_gpu,0);
float costtime_gpu;
// 4 count cpu time ////////////////////
cudaEvent_t start_cpu,stop_cpu;
cudaEventCreate(&start_cpu);
cudaEventCreate(&stop_cpu);
cudaEventRecord(start_cpu,0);
float costtime_cpu;
// mem malloc on host //////////////////
cudaMalloc((void**)&dev_a, N * sizeof(int));
cudaMalloc((void**)&dev_b, N * sizeof(int));
cudaMalloc((void**)&dev_c, N * sizeof(int));
// init a,b ////////////////////////////
for (int i=0;i<N; i++)
{
a[i] = -i;
b[i] = i * i;
}
// cpu time begin //////////////////////////////////////////////
cudaEventRecord(start_cpu,0);
for (int j=0;j<N; j++)
{
host_c[j]=a[j]+b[j];
}
cudaEventRecord(stop_cpu,0);
cudaEventSynchronize(stop_cpu);
cudaEventElapsedTime(&costtime_cpu,start_cpu,stop_cpu);
printf("cpu time is %f\n",costtime_cpu);
// cpu time end ///////////////////////////////////////////////
// gpu time begin //////////////////////////////////////////////
cudaEventRecord(start_gpu,0);
cudaMemcpy( dev_a, a, N * sizeof(int), cudaMemcpyHostToDevice );
cudaMemcpy( dev_b, b, N * sizeof(int), cudaMemcpyHostToDevice );
fun_vec_add_blockthread<<<128,128>>>(dev_a,dev_b,dev_c);
cudaMemcpy( c, dev_c, N * sizeof(int), cudaMemcpyDeviceToHost );
cudaEventRecord(stop_gpu,0);
cudaEventSynchronize(stop_gpu);
cudaEventElapsedTime(&costtime_gpu,start_gpu,stop_gpu);
printf("gpu time is %f\n",costtime_gpu);
// gpu time end ////////////////////////////////////////////////
bool success = true;
for (int i=0; i< N; i++)
{
if ((host_c[i])!= c[i])
{
printf("Error : %d +%d != %d \n",a[i],b[i],c[i]);
success = false;
}
}
if (success)
{
printf("done!\n");
}
cudaFree(dev_a);
cudaFree(dev_b);
cudaFree(dev_c);
return 0;
}
predef.h的定义如下
# define N (33 * 1024)
fun_gpu_add_blockthread.h的定义如下
__global__ void fun_vec_add_blockthread(int *a, int *b, int *c)
{
int tid = threadIdx.x + blockIdx.x * blockDim.x;;
while (tid < N)
{
c[tid] = a[tid] + b[tid];
tid += blockDim.x * gridDim.x;
}
}
//////////////////////////////////////////////////
// outline
// change the add into add threadIdx version
// mod : 2013年 10月 25日 星期五 16:34:30 CST