Boost Libraries: Timer

在寫程式的時候,我們常常會希望知道程式總共跑了多久,或是某個 function 需要執行多久,來瞭解我們的 performance。通常會使用的方法是利用 time.h 裡面的 clock() 來達到我們想要的目的,程式大概會長這樣:
#include <ctime>
#include <iostream>

using namespace std ;

int main( void ) {
   clock_t t = clock() ;
   // do something....
   cout << "The program runs " << (clock()-t)/CLK_TCK << 
   " seconds" << endl ;
   return 0 ;
}

這樣當然是沒啥不好的,不過人總是懶惰,有時候會覺得要寫那麼多行 code 是很麻煩的事情。所以就有了 boost::timer 的誕生。
Boost timer 的使用相當簡單,基本上只有三個 class。接下來就一一介紹。

Class Timer
timer 這個 class 會測量經過的時間,通常使用在程式當中一些比較繁瑣的 timing 測量方面。實做其實就是利用上面講過的 clock() function。要注意的是,timer 最多可以測量的時間大概是 596.5 小時(或是更少)。以下是一個簡單的例子:
#include <boost/timer.hpp>
#include <iostream>

using namespace std ;
using namespace boost ;

int main( void ) {
  timer t1 ;
  // do something..
  cout << t1.elapsed() << endl ;

  return 0 ;
}

如此便可以輸出 t1 這個 timer 經過的時間。

Class progress_timer
progress_timer 跟 timer 很相似,差別是在它會自動在 destruction 的時候輸出 progress_timer 所經過的時間。例子如下:
#include <boost/progress.hpp>
int main()
{
   progress_timer t;  // start timing
   // do something ...
   return 0;
}

如此程式會於結束的時候輸出如 0.06 s 之類的訊息:

Class progress_display
progress_display 這個 class 則就是傳統我們會看到的 progress bar 功能。這個只是要給人看,讓人知道這隻程式正在跑。舉例來說,如果我們想要來在 map 當中插入 element,在插入的途中想利用 progress_display 來知道進度,可以用以下的 code:
#include <boost/progress.hpp>
#include <map>
#include <iostream>

using namespace std ;
using namespace boost ;

int main( void ) {
  map big_map ;
  progress_display show_progress( 1000000 ) ;

  for ( int i = 0 ; i < 1000000 ; i++ ) {
    big_map.insert( make_pair(i,i) ) ;
    ++show_progress ;
  }

  return 0 ;
}
在大約有 70% 的 element 被插入時,progress_display 會顯示
0%   10   20   30   40   50   60   70   80   90   100%
|----|----|----|----|----|----|----|----|----|----|
************************************