本博客已遷往http://coredumper.cn
CUDA Runtime API提供了用於計時的接口,可以用如下代碼對在GPU上運行的CUDA程序進行計時,計時結果以毫秒爲單位:
cudaEvent_t start, stop;
cudaEventCreate(&start);
cudaEventCreate(&stop);
cudaEventRecord(start, 0);
//需要計時的在GPU上運行的程序
cudaEventRecord(stop, 0);
cudaEventSynchronize(stop);
float kernelTime;
cudaEventElapsedTime(&kernelTime, start, stop);
cudaEventDestroy(start);
cudaEventDestroy(stop);
printf("Kernel time: %.2f ms\n", kernelTime);
需要注意的是函數cudaEventSynchronize() 不可或缺,因爲CUDA的kernel函數是以異步方式執行的,調用後立刻返回,這會導致計時不準確。cudaEventSynchronize(stop)會使得直到GPU執行完cudaEventRecord(stop, 0)之前的所有語句時,事件stop纔會被記錄下來,即起到同步的作用。