通过progress_timer组件扩展计时精度

 
//通过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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值