1. 有時候我們要計算程式執行的時間.比如我們要對演算法進行時間分析,這個時候可以使用下面這個函數.
精確到us。
#include <sys/time.h> int gettimeofday(struct timeval *tv,struct timezone *tz); strut timeval { long tv_sec; /* 秒數 */ long tv_usec; /* 微秒數 */ }; gettimeofday將時間儲存在結構tv之中.tz一般我們使用NULL來代替. #include <sys/time.h< #include <stdio.h< #include <math.h< void function() { unsigned int i,j; double y; for(i=0;i<1000;i++) for(j=0;j<1000;j++) y=sin((double)i); } main() { struct timeval tpstart,tpend; float timeuse; gettimeofday(&tpstart,NULL); function(); gettimeofday(&tpend,NULL); timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+ tpend.tv_usec-tpstart.tv_usec; timeuse/=1000000; printf("Used Time:%f\n",timeuse); exit(0); }
這個程式輸出函數的執行時間,我們可以使用這個來進行系統效能的測試,或者是函數演算法的效率分析.在我機器上的一個輸出結果是: Used Time:0.556070
2.第二種是我自己經常用的,就是:
在執行程式前,加time,如:輸入time./abc ,精確到ms。
3. clock函數(精確到1/CLOCKS_PER_SEC秒,毫秒級)
#include <iostream>
#include <ctime>
using namespace std;
int max(int x,int y)
{
return (x>y)?x:y;
}
int main()
{
const double begin=clock();
for(int i=10000;i>0;i--)
for(int j=10000;j>0;j--)
max(i,j);
const double end=
clock();
cout <<begin<<" "<<end;
return 0;
}