boost::timer

作用:

用来计时。

 

使用方法:
timer类初始化时,开始计时。

调用 elapsed() 时计时结束,返回 double 型,单位为秒。

调用 restart() 重新开始计时。

 

注:

elapsed_max() 和 elapsed_min() 这两个函数用来输出该类能计时的最大和最小范围,前者单位是小时,后者是秒。测试精度是由操作系统或编译器决定的。1.49版的精度为:

最大:2.14748e+09(h)    最小:1e-06(s)

  #include <iostream>
  #include <boost/timer.hpp>
int main() { boost::timer t; //开始计时 std::cout<<"最大值(h)"<<t.elapsed_max()<<std::endl; std::cout<<"最小值(s)"<<t.elapsed_min()<<std::endl; int j = 10; for(int i = 0;i < 100000000; i++) { j = (j+1)*3/3; } std::cout<<"运行时长(s)"<<t.elapsed()<<std::endl; t.restart(); std::cout<<"运行时长(s)"<<t.elapsed()<<std::endl; }

 

源代码:timer.hpp:

View Code
 1   #ifndef BOOST_TIMER_HPP
 2   #define BOOST_TIMER_HPP
 3 
 4   #include <ctime>
 5   #include <boost/limits.hpp>
 6   #include <boost/config.hpp>
 7 
 8   #ifdef BOOST_NO_STDC_NAMESPACE
 9       namespace std{ using ::clock_t; using ::clock; }
10   #endif
11 
12   namespace boost{
13       class timer
14       {
15           public:
16               timer(){ _start_time = std::clock(); }
17               void restart() { _start_time = std::clock(); }
18               double elapsed() const { return double(std::clock() - _start_time) /CLOCKS_PER_SEC; }
19               double elapsed_max() const { return double((std::numeric_limits<std::clock_t>::max)()) - double(_start_time) / double(CLOCKS_PER_SEC);}
20               double elapsed_min() const { return double(1) /double(CLOCKS_PER_SEC);}
21           private:
22               std::clock_t _start_time;
23       };
24   }
25   #endif

 

posted @ 2012-09-13 12:33  轻典  阅读(593)  评论(0编辑  收藏  举报