1. 程式人生 > >計算C語言程式執行時間

計算C語言程式執行時間

在c語言中有專門處理系統時間,程式計時等等功能的庫,
即time.h
在time.h中函式clock_t clock( void )可以完成計時功能。

這個函式返回從“開啟這個程式程序”到“程式中呼叫clock()函式”時之間的CPU時鐘計時單元(clock tick)數,在MSDN中稱之為掛鐘時間(wal-clock)。其中clock_t是用來儲存時間的資料型別,在time.h檔案中,我們可以找到對它的定義:
#ifndef _CLOCK_T_DEFINED
typedef long clock_t;
#define _CLOCK_T_DEFINED
#endif

很明顯,clock_t是一個長整形數。在time.h檔案中,還定義了一個常量CLOCKS_PER_SEC,它用來表示一秒鐘會有多少個時鐘計時單元,其定義如下:

#define CLOCKS_PER_SEC ((clock_t)1000)

可以看到每過千分之一秒(1毫秒),呼叫clock()函式返回的值就加1。

下面這個程式計算了迴圈1千萬次所用的時間:

#include “stdio.h”
#include “stdlib.h”
#include “time.h”

int main(int argc, const char *argv[])
{
int i = 10000000;
double start, end;
start = clock();
while( i-- ) ;
end = clock();
printf("the run time is:%f s\n",(end-start)/CLOCKS_PER_SEC);
exit(EXIT_SUCCESS);
}


執行結果如下:

the run time is 0.025000 s