close

相關範例及內容參考 http://ivanlife.wordpress.com/2011/05/09/time-cuda/

本篇介紹使用cudaEvent的方式

其他用法請參考上述網址

 

主要分成幾個部分:

  1. 宣告時間變數
    cudaEvent_t start, stop; //用於紀錄開始與結束當下的時間
    float time; //計算時間用

  2. create 事件
    cudaEventCreate(&start);
    cudaEventCreate(&stop);

  3. 開始記錄時間
    分別在計算時間的開頭及結束使用
    cudaEventRecord(start, 0);
    cudaEventRecord(stop, 0);

  4. 同步CPU與GPU時間
    避免device還沒做完,就先記錄結束時間
    cudaEventSynchronize(stop);
    =>後來發現cudaThreadSynchronize()跟cudaEventSynchronize()完全是兩個不同的function啊,為何當時都沒發現......
         擺放的位置不太一樣,要注意。

  5. 計算時間
    並將結果存入一開始宣告的float變數中
    cudaEventElapsedTime(&time, start, stop);

完整範例如

cudaEvent_t start, stop;
float time;
cudaEventCreate(&start);
cudaEventCreate(&stop);
 
cudaMalloc((void **) &a_d, size);   // Allocate array on device
cudaMemcpy(a_d, a_h, size, cudaMemcpyHostToDevice);
cudaEventRecord(start, 0);
// Do calculation on device:
square_array <<< n_blocks, block_size >>> (a_d, N);
cudaEventRecord(stop, 0);
cudaEventSynchronize(stop);
 
// Retrieve result from device and store it in host array
cudaMemcpy(a_h, a_d, sizeof(float)*N, cudaMemcpyDeviceToHost);
cudaFree(a_d);
cudaEventElapsedTime(&time, start, stop);
printf ("Time for the kernel: %f ms\n", time);

 

 

 

 

 

 

 

需特別注意

4.同步CPU與GPU時間

否則計算的時間可能會有錯誤

關於cudaThreadSynchronize()

請參考

http://developer.download.nvidia.com/compute/cuda/4_1/rel/toolkit/docs/online/group__CUDART__THREAD__DEPRECATED_g6e0c5163e6f959b56b6ae2eaa8483576.html

但官方表示因為此函式名字無法明確表達出它的功能,傾向建議使用cudaDeviceSynchronize()

關於此函式,可從上方網址找到其連結

 

也可參見http://www.ptt.cc/bbs/C_and_CPP/M.1227119415.A.BB5.html 中的第六招

有中文說明

 

arrow
arrow

    holmes310524 發表在 痞客邦 留言(0) 人氣()