close

  因為嵌入式系統的第一個作業要做 timer task,所以 survey 了一下並 try 了幾行 code,參考 C/C++ API 與範例後,才知道 standard C/C++ 最小就定義到秒,要更小就要靠 OS 和 compiler 支援了,例如在 Linux 可以用 gettimeofday() 算到 mili-second,Windows 可以用 QueryPerformanceFrequency() 和 QueryPerformance Counter() 逼近到 micro-second。
  我用 Dev-C++ 來寫,基本的 time function 定義在  裡,如果想要比"秒"更精確可以用 clock() 或參考 Dev 特有的 。
  clock() 回傳的 type clock_t 其實是個 rate,是 system clocks 或 frequency,所以要轉換成時間,例如用 CLOCKS_PER_SEC 這個常數。在我的 Windows 平台上這值等於 1000,所以已經精確至 mili-second 了;在我的 Linux 平台上為 128。
  Dev 獨特的定義 timeb 這個 tyoe,讓使用者可以直接取得 mili-second。
  我寫了個範例程式,利用 sleep() 來消耗時間,gcc/g++ 是要 #include ,在 Dev-C++ 是用 #include   的 Sleep();
注意!sleep(秒) Sleep(毫秒)。


/*
 * 在 Dev-C++ for Windows 之上,
 * 如何取得系統時間以及計算 subroutine 的 execution time
 */

#include
#include
#include
#include
#include

int main()
{
 time_t timer = time(NULL);
 cout cout 
 clock_t clocker = clock();
 cout 
 // time() 是 call by reference,所以也可以這樣用
 time_t start,end;
 time(&start);
 Sleep(1234);     // 程式暫停 1.234 秒
 cout time(&end);
 cout 
 // 算算看 sleep() 空耗的時間
 clocker = clock();
 timeb begin;
 ftime(&begin);
 for(int i=0 ; i {
  Sleep(800);
  cout  if((i+1)%10 == 0)   cout }
 cout cout // 把 clock 數換成秒數
 // CLK_PER_SEC = CLOCKS_PER_SEC = CLK_TCK
 cout 
 timeb left;
 ftime(&left);

 short minisecs;
 if(left.millitm > begin.millitm)  minisecs = left.millitm - begin.millitm;
 else  begin.millitm - left.millitm;
 cout system("pause");
 
 return 0;
}


結果如下:

從 1970, 1/1, 00:00:00 開始算,已經經過: 1254411050 秒了
現在本機 OS (Windows XP) 時間: Thu Oct 01 23:30:50 2009


The start clock = 15
The end clock = 1249
The duration = 1
.....
 The duration = 4063 clocks
    Also about 4 seconds
共經過 4.062 秒
請按任意鍵繼續 . . .


 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 小郭阿利 的頭像
    小郭阿利

    小郭阿利的網路日誌

    小郭阿利 發表在 痞客邦 留言(0) 人氣()