C 庫 - clock() 函式



C 庫的 clock() 函式返回程式啟動以來經過的時鐘滴答數。要獲取 CPU 使用的秒數,我們需要除以 CLOCKS_PER_SEC。在 CLOCKS_PER_SEC 等於 1000000 的 32 位系統上,此函式大約每 72 分鐘返回相同的值。

CLOCKS_PER_SEC 是一種用於構建時間程式的宏。

語法

以下是 C 庫 clock() 函式的語法:

clock_t clock(void)

引數

  • 此函式不接受任何引數。

返回值

此函式返回程式啟動以來經過的時鐘滴答數。如果失敗,則返回 -1。

示例 1

以下是一個基本的 C 庫程式,用於演示 clock() 函式。

#include <time.h>
#include <stdio.h>

int main () {
   clock_t start_t, end_t;
   double total_t;
   int i;

   start_t = clock();
   printf("Starting of the program, start_t = %ld\n", start_t);
    
   printf("Going to scan a big loop, start_t = %ld\n", start_t);
   for(i=0; i< 10000000; i++) {
   }
   end_t = clock();
   printf("End of the big loop, end_t = %ld\n", end_t);
   
   total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
   printf("Total time taken by CPU: %f\n", total_t  );
   printf("Exiting of the program...\n");

   return(0);
}

以上程式碼產生以下結果:

Starting of the program, start_t = 1194
Going to scan a big loop, start_t = 1194
End of the big loop, end_t = 26796
Total time taken by CPU: 0.025602
Exiting of the program...

示例 2

在本例中,我們使用 clock() 函式演示了各種操作的處理器時間(以秒為單位)的測量。

#include <stdio.h>
#include <time.h>
#include <math.h>

int main() {
   float a;
   clock_t time_req;

   // Measure time for multiplication
   time_req = clock();
   for (int i = 0; i < 200000; i++) {
        a = log(i * i * i * i);
   }
   time_req = clock() - time_req;
   printf("Processor time taken for multiplication: %f seconds\n", (float)time_req / CLOCKS_PER_SEC);

   // Measure time using pow function
   time_req = clock();
   for (int i = 0; i < 200000; i++) {
       a = log(pow(i, 4));
   }
   time_req = clock() - time_req;
   printf("Processor time taken in pow function: %f seconds\n", (float)time_req / CLOCKS_PER_SEC);

   return 0;
}

輸出

執行以上程式碼後,我們得到以下結果:

Processor time taken for multiplication: 0.005235 seconds
Processor time taken in pow function: 0.010727 seconds
廣告