如何在 C 中計算函式花費的時間?
在這裡,我們將瞭解如何計算該程序花費的時間。對於此問題,我們將使用 clock() 函式。time.h 標頭檔案中有 clock()。
為了獲得經過時間,我們可以在開始時和任務結束時使用 clock() 來獲取時間,然後減去這些值以獲得差異。在此之後,我們將該差異除以 CLOCK_PER_SEC(每秒時鐘滴答數)以獲取處理器時間。
示例
#include <stdio.h> #include <time.h> void take_enter() { printf("Press enter to stop the counter
"); while(1) { if (getchar()) break; } } main() { // Calculate the time taken by take_enter() clock_t t; t = clock(); printf("Timer starts
"); take_enter(); printf("Timer ends
"); 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
廣告