progress_timer
头文件
#include <boost/progress.hpp>
using namespace boost;
用法
progress_timer VS timer
-
progress_timer
继承自timer,是一个定时器, 可以像timer那样使用。
-
优点是:当退出作用域的时候,会调用析构函数,自动输出距定义progress_timer的时间,省去了手动调用timer的elapsed的工作。
#include <boost/progress.hpp>
using namespace boost;
int main() {
progress_timer t;
return 0;
}
测量多个时间
- 如果要测量多个时间,可以用{}限定
progress_timer
生命周期。
#include <boost/progress.hpp>
using namespace boost;
int main() {
{
progress_timer t;
}
{
progress_timer t;
}
return 0;
}
输出重定向
progress_timer
的构造函数中有一个参数std::ostream & os = std::cout,表示默认输出到std::cout;当然,我们可以将析构时的输出定向到其他IO流里面。
#include <boost/progress.hpp>
#include <sstream>
using namespace boost;
int main() {
std::stringstream ss;
{
progress_timer t(ss);
}
std::cout << ss.str();
return 0;
}
源码学习
class progress_timer : public timer, private noncopyable
{
public:
explicit progress_timer( std::ostream & os = std::cout )
: m_os(os) {}
~progress_timer()
{
try
{
//std::istream::fixed,std::istream::floatfield 表示采用顶点计数法 https://blog.csdn.net/xionghui96/article/details/108307472
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" // elapsed() 表示调用timer的 elapsed()函数
<< 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的目的就是为了简化timer的调用,其他没什么。