在寫代碼中,有時候我們需要評估某段代碼或者函數的執行時間;方法就是在該段代碼或者函數前面,記錄一個時間T1,在代碼段或函數后面記錄時間T2,那其運行時間就是T2-T1;
就是簡單的減法!!!
那具體的實現方法呢?我這里有兩個,給大家參考:
一,clock();
clock()是C/C++中的計時函數,而與其相關的數據類型是clock_t;頭文件:time.h;
typedef long clock_t;可見clock_t為長整型;
在time.h文件中,還定義了一個
常量
CLOCKS_PER_SEC,它用來表示一秒鍾會有多少個時鍾計時單元,其定義如下:
#define CLOCKS_PER_SEC ((clock_t)1000)
例子:
#include <stdio.h>
#include <
stdlib.h>
#include <time.h>
int main(void)
{
long i = 10000000L;
clock_t start, finish;
double duration;
/* 測量一個事件持續的時間*/
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");
}
二,另一種形式就是timeval結構體,定義如下:
struct timeval
{
time_t tv_sec; /* Seconds. */
suseconds_t tv_usec; /* Microseconds. */
};
{
time_t tv_sec; /* Seconds. */
suseconds_t tv_usec; /* Microseconds. */
};
例子:
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
int main(int argc, char * argv[])
#include <sys/time.h>
#include <time.h>
int main(int argc, char * argv[])
{
struct timeval tv; //定義
while(1){
gettimeofday(&tv, NULL); //獲取時間
printf("time %u:%u\n", tv.tv_sec, tv.tv_usec);
sleep(2);
}
return 0;
}
struct timeval tv; //定義
while(1){
gettimeofday(&tv, NULL); //獲取時間
printf("time %u:%u\n", tv.tv_sec, tv.tv_usec);
sleep(2);
}
return 0;
}
兩種方法的區別:
1,若是粗略的計算,都可以使用;
2,區別在於定義上:clock的最小精度為毫秒(ms);使用的節拍來定義;
timeval精確到微秒(us),獲取的是系統時間,而且還有秒;
具體的使用,根據實際情況來決定!祝大家的代碼中bug越來越少。