Boost库学习------progress_timer

Boost库中的progress_timer类提供了一种简洁的方法来显示时间间隔,它在构造后到析构期间自动计算并输出时间。在main函数中,通过创建和销毁progress_timer对象可以方便地测量不同部分的执行时间。如果需要更高精度,可以继承progress_timer并修改输出精度以满足需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.progress_timer继承自timer,实现了timer的所有功能,但是比timer更加简单,不用显示调用elapsed()函数来显示时间间隔,它的析构函数自动调用了elapsed(),也就是说当它创建后到析构这段时间会自动显示。

int main(){

progress_timer pt;

..........

}

当pt的作用于结束时,自动输出创建到销毁的时间。

还可以记录多个作用于的时间,例如:

int main(){

{

   progress_timer pt1;

}

...........

{

progress_timer pt2;

}

}


progress_timer源码十分简洁:

class progress_timer : public timer, private noncopyable
{
  
 public:
  explicit progress_timer( std::ostream & os = std::cout ) : m_os(os) {}
  ~progress_timer()
  {
  //  A) Throwing an exception from a destructor is a Bad Thing.
  //  B) The progress_timer destructor does output which may throw.
  //  C) A progress_timer is usually not critical to the application.
  //  Therefore, wrap the I/O in a try block, catch and ignore all exceptions.
    try
    {
      // use istream instead of ios_base to workaround GNU problem (Greg Chicares)
      std::istream::fmtflags old_flags = m_os.setf( std::istream::fixed,
                                                   std::istream::floatfield );
      std::streamsize old_prec = m_os.precision( 2 );
      m_os << elapsed() << " s\n" // "s" is System International d'Unites std
                        << std::endl;
      m_os.flags( old_flags );
      m_os.precision( old_prec );
    }

    catch (...) {} // eat any exceptions
  } // ~progress_timer

 private:
  std::ostream & m_os;
};
可以看到,progress_timer用一个特定的流进行初始化,默认为标准输出流。当对象被析构时会把时间间隔自动输出到指定的流中。

从代码中可以看到,输出只精确到了小数点后2位,如果我们需要更精确的输出,根据开放封闭原则,可以继承progress_timer,从而改变输出精度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值