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(定向到指定的文件中去)。