您的位置:首页 > 其它

Boost库学习------progress_timer

2013-09-13 15:17 417 查看
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,从而改变输出精度。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  boost