Cod*_*der 0 c c++ linux time cuda
我有一个cuda代码,可以在GPU上执行计算.我正在使用clock(); 找出时间
我的代码结构是
__global__ static void sum(){
// calculates sum
}
extern "C"
int run_kernel(int array[],int nelements){
clock_t start, end;
start = clock();
//perform operation on gpu - call sum
end = clock();
double elapsed_time = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("time required : %lf", elapsed_time);
}
Run Code Online (Sandbox Code Playgroud)
但是时间总是0.0000我检查了打印开始和结束时间.Start有一些值,但结束时间总是为零.
知道可能是什么原因?任何衡量时间的替代方案.
任何帮助,将不胜感激.
谢谢
这里有两个问题:
clock()功能的分辨率太低,无法测量您尝试计时的事件的持续时间CUDA有自己的高精度定时API,它是在GPU上运行的定时操作的推荐方法.使用它的代码看起来像这样:
int run_kernel(int array[],int nelements){
cudaEvent_t start,stop;
cudaEventCreate(&start);
cudaEventCreate(&stop);
cudaEventRecord(start, 0);
//
//perform operation on gpu - call sum
//
cudaEventRecord(stop, 0);
cudaEventSynchronize(stop);
float elapsedTime;
cudaEventElapsedTime(&elapsedTime, start, stop);
printf("time required : %f", elapsed_time);
cudaEventDestroy(start);
cudaEventDestroy(stop);
}
Run Code Online (Sandbox Code Playgroud)
不要clock用来计算CUDA内核的启动时间.使用cudaEventElapsedTime.即使clock精度足够高以计算内核的时间(事实并非如此),内核启动也是异步的,这意味着控制流在内核完成之前返回到调用函数.
这是如何做:
void run_kernel(...)
{
// create "events" which record the start & finish of the kernel of interest
cudaEvent_t start, end;
cudaEventCreate(&start);
cudaEventCreate(&end):
// record the start of the kernel
cudaEventRecord(start);
// perform operation on gpu - call sum
sum<<<...>>>(...);
// record the end of the kernel
cudaEventRecord(end);
// get elapsed time. Note that this call blocks
// until the kernel is complete
float ms;
cudaEventElapsedTime(&ms, start, end);
printf("time required : %f milliseconds", ms);
cudaEventDestroy(start);
cudaEventDestroy(end);
}
Run Code Online (Sandbox Code Playgroud)