c++ boost progress_timer

boost库中的progress_timer类继承自timer,使用也是相似的。
值得注意 的是,progress_timer类不需要调用elapsed()方法,它会在析构的时候自动输出花费时间,下面是它的源代码。

class progress_timer : public timer, private noncopyable
{

 public:
  explicit progress_timer( std::ostream & os = std::cout )
     // os is hint; implementation may ignore, particularly in embedded systems
     : timer(), noncopyable(), 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;
};

下面我通过一个例子来看下具体的使用:

#include <boost\progress.hpp>
using namespace boost;

#include <sstream>
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    {
        int i = 0;
        progress_timer timers;
        while (i < 10000000)
        {
            i++;
        }
    }

    stringstream ss;
    {
        int i = 0;
        progress_timer timers(ss);
        while (i < 10000000)
        {
            i++;
        }
    }
    cout << ss.str() << endl;

    ofstream out("out.txt"); ;

    {
        int i = 0;
        progress_timer timers(out);
        while (i < 10000000)
        {
            i++;
        }
    }
    out.flush();
    out.close();

    return 0;
}

在上面的例子中,我是用{}来限定progress_timer的声明周期,在它的生命周期结束后,会自动调用析构函数,输出消耗时间。

相信大家都注意到了,progress_timer类的构造函数是可以接收输出流的,它允许在析构的时候输出定向到指定的输出流中去,默认是std::cout。

在上面的例子中,分别将它的输出定向到了stringstream(可以转化为字符串供后续使用),ofstream(定向到指定的文件中去)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值