Latest web development tutorials

C 庫函數– clock()

C 標準庫 - <time.h> C標準庫- <time.h>

描述

C庫函數clock_t clock(void)返回程序執行起(一般為程序的開頭),處理器時鐘所使用的時間。 為了獲取CPU 所使用的秒數,您需要除以CLOCKS_PER_SEC。

在32 位系統中,CLOCKS_PER_SEC 等於1000000,該函數大約每72 分鐘會返回相同的值。

聲明

下面是clock() 函數的聲明。

clock_t clock(void)

參數

  • NA

返回值

該函數返回自程序啟動起,處理器時鐘所使用的時間。 如果失敗,則返回-1 值。

實例

下面的實例演示了clock() 函數的用法。

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

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

   start_t = clock();
   printf("程序启动,start_t = %ld\n", start_t);
    
   printf("开始一个大循环,start_t = %ld\n", start_t);
   for(i=0; i< 10000000; i++)
   {
   }
   end_t = clock();
   printf("大循环结束,end_t = %ld\n", end_t);
   
   total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
   printf("CPU 占用的总时间:%f\n", total_t  );
   printf("程序退出...\n");

   return(0);
}

讓我們編譯並運行上面的程序,這將產生以下結果:

程序启动,start_t = 0
开始一个大循环,start_t = 0
大循环结束,end_t = 20000
CPU 占用的总时间:0.000000
程序退出...

C 標準庫 - <time.h> C標準庫- <time.h>