C++計(jì)時(shí)具體操作方法詳解
C++編程語言應(yīng)用范圍廣泛,功能強(qiáng)大,我們?cè)谏掀恼轮芯鸵呀?jīng)對(duì)C++時(shí)間的基本概念進(jìn)行了一個(gè)簡(jiǎn)單的介紹?,F(xiàn)在,我們將進(jìn)一步對(duì)C++計(jì)時(shí)的具體操作進(jìn)行解讀,讓大家能從中獲得更多的知識(shí)。#t#
C++計(jì)時(shí)操作中所用到的函數(shù)是clock(),而與其相關(guān)的數(shù)據(jù)類型是clock_t。在MSDN中,查得對(duì)clock函數(shù)定義如下:
clock_t clock( void );
這個(gè)C++計(jì)時(shí)的函數(shù)返回從“開啟這個(gè)程序進(jìn)程”到“程序中調(diào)用clock()函數(shù)”時(shí)之間的CPU時(shí)鐘計(jì)時(shí)單元(clock tick)數(shù),在MSDN中稱之為掛鐘時(shí)間(wal-clock)。其中clock_t是用來保存時(shí)間的數(shù)據(jù)類型,在time.h文件中,我們可以找到對(duì) 它的定義:
- #ifndef _CLOCK_T_DEFINED
- typedef long clock_t;
- #define _CLOCK_T_DEFINED
- #endif
很明顯,clock_t是一個(gè)長(zhǎng)整形數(shù)。在time.h文件中,還定義了一個(gè)常量CLOCKS_PER_SEC,它用來表示一秒鐘會(huì)有多少個(gè)時(shí)鐘計(jì)時(shí)單元,其定義如下:
#define CLOCKS_PER_SEC ((clock_t)1000)
可以看到每過千分之一秒(1毫秒),調(diào)用clock()函數(shù)返回的值就加1。下面舉個(gè)C++計(jì)時(shí)的例子,你可以使用公式clock()/CLOCKS_PER_SEC來計(jì)算一個(gè)進(jìn)程自身的運(yùn)行時(shí)間:
- void elapsed_time()
- {
- printf("Elapsed time:%u secs.\n",clock()/CLOCKS_PER_SEC);
- }
當(dāng)然,你也可以用clock函數(shù)來計(jì)算你的機(jī)器運(yùn)行一個(gè)循環(huán)或者處理其它事件到底花了多少時(shí)間:
- #include “stdio.h”
- #include “stdlib.h”
- #include “time.h”
- int main( void )
- {
- long i = 10000000L;
- clock_t start, finish;
- double duration;
- /* 測(cè)量一個(gè)事件持續(xù)的時(shí)間*/
- printf( "Time to do %ld empty loops is ", i );
- start = clock();
- while( i-- ) ;
- finish = clock();
- duration = (double)(finish - start) / CLOCKS_PER_SEC;
- printf( "%f seconds\n", duration );
- system("pause");
- }
在筆者的機(jī)器上,C++計(jì)時(shí)操作后的運(yùn)行結(jié)果如下:
Time to do 10000000 empty loops is 0.03000 seconds
上面我們看到時(shí)鐘計(jì)時(shí)單元的長(zhǎng)度為1毫秒,那么計(jì)時(shí)的精度也為1毫秒,那么我們可不可以通過改變CLOCKS_PER_SEC的定義,通過把它定義的大一些,從而使C++計(jì)時(shí)的精度更高呢?通過嘗試,你會(huì)發(fā)現(xiàn)這樣是不行的。在標(biāo)準(zhǔn)C/C++中,最小的計(jì)時(shí)單位是一毫秒。


















