boost -- cpu_timer

很多时候我们需要计算程序的运行时间来检查程序的效率,利用boost中的 boost::timer库可以很容易完成这项任务。

 

所需头文件: <boost/timer/timer.hpp>

名字空间   : boost::timer

类            :cup_timer, auto_cpu_timer 

 

 先来看下cpu_timer,这个类的接口很简单:

 

 1 void cpu_timer::start() noexcept;            // 开始一个计时器
 2 void cpu_timer::stop()  noexcept;            // 结束一个计时器
 3 void cpu_timer::resume() noexcept;           // 如果已经调用了stop,resume可以继续进行计时 
 4 bool cpu_timer::is_stopped() noexcept;       // 计时器是否已经停止计时(call stop() ), 
 5  cpu_times cpu_timer::elapsed() noexcept;  // 如果is_stopped(),那么返回从 计时开始 至 stop()之间的时间间隔;
 6                                            // 否则, 返回从 计时开始 至 调用此函数 的时间间隔
 7  std::string format(int places, const string &format)const;
 8  std::string format(int places = default_places) const;
 9                                     //  返回 elapsed的字符串形式
10                                     //  places代表精度,places = 3, 表示精确到小数点后3位,单位为秒
11                                     //  format代表格式化字符串 ,常用的是%w,表示cpu_times.wall

 

注:小心resume函数, resume并不是重新开始另一个计时器,而是在stop后继续本次计时;想要开始另一次计时,应该调用start

 

对于 elapsed()函数的返回类型:cpu_times,它表示了一个时间间隔: 

 

struct cpu_times

{
      nanosecond_type wall;       // most importent
      nanosecond_type user;
      nanosecond_type system;

      void clear();
};

 

 下面来看一个例子:

这个例子测试:使用std::move和不使用的效率差异: 

 

 1 #include <boost/timer/timer.hpp>

 2 #include <memory>
 3 #include <vector>
 4 #include <string>
 5 #include <iostream>
 6 
 7 using namespace std;
 8 using namespace boost::timer;
 9 
10 
11 vector<string> createVector_98()
12 {
13     vector<string> vec;
14     for (int i = 0; i < 10; ++i){
15             vec.emplace_back("helloworld");
16     }
17     return vec;
18 }
19 
20 vector<string> createVector_11()
21 {
22     vector<string> vec;
23     for (int i = 0; i < 100; ++i){
24         vec.emplace_back("helloworld");
25     }
26     return move(vec);
27 }
28 
29 int main()
30 {
31     const int TEST_TIMES = 100;
32 
33     vector<string> result;
34 
35     cpu_timer timer;
36     timer.start();
37     for (int i = 0; i < TEST_TIMES; ++i){
38         result = createVector_98();
39     }
40     cout << "no move" << timer.format(6) << endl;
41 
42     timer.start(); // don't call resume()
43     
44     for (int i = 0; i < TEST_TIMES; ++i){
45         result = createVector_98();
46     }
47     cout << "use move" << timer.format(6) << endl;
48 }

结果如下: 

 no move 0.025558s wall, 0.015600s user + 0.000000s system = 0.015600s CPU (61.0%)

use move 0.019096s wall, 0.031200s user + 0.000000s system = 0.031200s CPU (163.4%)

 

posted on 2012-09-14 11:59  sanlo  阅读(3757)  评论(0编辑  收藏  举报