首頁  >  文章  >  後端開發  >  如何在C語言中測量函數的執行時間?

如何在C語言中測量函數的執行時間?

WBOY
WBOY轉載
2023-08-28 14:21:06967瀏覽

如何在C語言中測量函數的執行時間?

在這裡,我們將看到如何計算進程所花費的時間。對於這個問題,我們將使用clock()函數。 clock()函數位於time.h頭檔中。

要取得經過的時間,我們可以在任務開始時使用clock()取得時間,在任務結束時再次使用clock()取得時間,然後將這兩個值相減得到差值。然後,我們將差值除以CLOCK_PER_SEC(每秒鐘的時脈滴答數)以取得處理器時間。

範例

#include <stdio.h>
#include <time.h>
void take_enter() {
   printf("Press enter to stop the counter </p><p>");
   while(1) {
      if (getchar())
      break;
   }
}
main() {
   // Calculate the time taken by take_enter()
   clock_t t;
   t = clock();
   printf("Timer starts</p><p>");
   take_enter();
   printf("Timer ends </p><p>");
   t = clock() - t;
   double time_taken = ((double)t)/CLOCKS_PER_SEC; // calculate the elapsed time
   printf("The program took %f seconds to execute", time_taken);
}

輸出

Timer starts
Press enter to stop the counter
Timer ends
The program took 5.218000 seconds to execute

以上是如何在C語言中測量函數的執行時間?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除