您的位置:首页 > 其它

boost学习2.3:progress_timer类(继承自timer)

2016-01-15 14:13 393 查看
progress_timer类

(1)是继承自timer,会在析构时自动输出时间(而不用手动调用elapsed函数)

(2)[b][b]progress_timer[/b]位于命名空间boost中,还有需要包含文件progress.hpp[/b]

#include <boost/progress.hpp>
using namespace boost;

(3)[b][b]progress_timer继承了timer的全部能力。[/b][/b]

[b][b] 可以用花括号在一个程序中进行多次计时操作。{。。。}{。。。}[/b][/b]

[b][b](4)自定义一个new_progress_timer类[/b][/b]

初始化函数:

// test1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<stdlib.h>
#include<iostream>
#include <boost/timer.hpp>
#include <boost/progress.hpp>
#include <boost/static_assert.hpp>
using namespace boost;
using namespace std;

template<int N=2 >//非类型模板参数
class new_progress_timer:public boost::timer//继承自timer
{
private:
std::ostream& m_os;
public:
new_progress_timer(std::ostream&os=std::cout):m_os(os)//初始化输出流到m_os
{
BOOST_STATIC_ASSERT(N>=0&&N<=10);//静态断言,保证N在0到10之间
}

~new_progress_timer(void)
{
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"//s表示秒
<<std::endl;

m_os.flags(old_flags);
m_os.precision(old_prec);
}
catch(...){}//析构函数绝对不能抛出异常(所以这里接受所有的异常)
}
};
template<>
class new_progress_timer<4>:public boost::progress_timer
{};//类模板的特化,这里取4,也就是当实例化为4的时候,这个时候不会再去调上面的
//而会直接调这里的,这里是直接从progress_timer继承。

int _tmain(int argc, _TCHAR* argv[])
{
new_progress_timer<3> t;
for(int i=0;i<100;i++)
cout<<endl;
//system("pause");
return 0;
}


View Code

  

  

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: