//通过progress_timer扩展计时精度
//原则上程序库的代码不能被用户修改,不过我们可以通过模板技术仿造progress_timer编写一个新类
//new_progress_timer以实现任意精度的输出
#include <iostream>
#include <boost/progress.hpp>
#include <boost/static_assert.hpp> //静态断言,控制精度范围在0~10以内
using namespace boost;
using namespace std;
template <int N = 2>
class new_progress_timer:public boost::timer{
public:
new_progress_timer(std::ostream& os = std::cout):m_os(os){
BOOST_STATIC_ASSERT(N >= 0 && N <= 10);
}
~new_progress_timer()//析构函数是核心功能,保存IO流状态,然后设定输出精度,完成输出后恢复IO流的状态
{
try
{
//保存流的状态
std::istream::fmtflags old_flags = m_os.setf(std::istream::fixed,std::istream::floatfield);
std::streamsize old_prec = m_os.precision(N);
//输出时间
m_os << elapsed() << " s\n" << std::endl;
//恢复流状态
m_os.flags(old_flags);
m_os.precision(old_prec);
}
catch(...){}//析构函数绝不能抛出异常
}
private:
std::ostream &m_os;
};
//使用模板特例化,精度为2
template<>
class new_progress_timer<2>:public boost::progress_timer{};
int main(){
new_progress_timer<10> t;//精度为10
unsigned int i;
int sum = 1;
for(i = 0; i < 1000000000; ++i)//10亿条指令
sum %= 2;
}
运行结果:
2.6560000000 s