您的位置:首页 > 其它

boost完全开发指南第2章-处理时间2(时间类timer)

2013-12-14 20:07 459 查看
0、timer(v1)库概述

Boost1.48以后的timer库由二个组件构成:早期timer(v1)和新的cpu_timer(v2), 前者使用标准C/C++接口,后者基于chrono库使用操作系统的api,计时精度更高。

早期timer(v1)由于精度不高已被废弃,其中包括:计时器类timer、progress_timer、进度指示类progress_display。

1、timer

//timer_demo.hpp
#include <iostream>
#include <boost/timer.hpp>

using namespacestd;
using namespaceboost;

void timer_test()
{
timer t;
cout<<"max timespan:"<<t.elapsed_max()<<endl;
cout<<"min timespan:"<<t.elapsed_min()<<endl;
cout<<"now time elapsed:"<<t.elapsed()<<endl;
}


2、progress_timer

// progress_timer_demo.hpp

#include <iostream>
#include <sstream>
#include <boost/progress.hpp>

using namespacestd;
using namespaceboost;

void progress_timer_test()
{
//first timer
{
boost::progress_timerpt_first;
}

//second timer
stringstream ss;
{
boost::progress_timerpt_second(ss);//输出到stringstream
}
cout<<ss.str()<<endl;
}


3、new_progress_timer

#include <boost/progress.hpp>
#include <boost/static_assert.hpp>

template <intN=2>
class new_progress_timer :publicboost::timer
{
public:
new_progress_timer(std::ostream&os):m_os(os)
{
BOOST_STATIC_ASSERT(N >=0 &&N<=10);
}

~new_progress_timer(void)
{
try
{
std::istream::fmtflagsold_flgs =m_os.setf(std::istream::fixed,std::istream::floatfield);
std::streamsizeold_prec=m_os.precision(N);
//output time
m_os<<elapsed()<<"s"<<endl;
//retore
m_os.flags(old_flgs);
m_os.precision(old_prec);

}catch(...)
{}
}
private:
std::ostream  &m_os;
};

void new_progress_timer_test()
{
new_progress_timer<11> npt(std::cout);
}


(1)如果N>10

编译出错:

1>------ Build started: Project: vs_demo, Configuration: Debug Win32------

1>Compiling...

1>main.cpp

1>f:\boost_dev\boostdevguide\vs_demo\progress_timer_demo.hpp(34) : errorC2027: use of undefined type 'boost::STATIC_ASSERTION_FAILURE<x>'

1> with

1> [

1> x=false

1> ]

1> f:\boost_dev\boostdevguide\vs_demo\progress_timer_demo.hpp(32) : whilecompiling class template member function 'new_progress_timer<N>::new_progress_timer(std::ostream&)'

1> with

1> [

1> N=11

1> ]

1> f:\boost_dev\boostdevguide\vs_demo\progress_timer_demo.hpp(59) : seereference to class template instantiation 'new_progress_timer<N>' beingcompiled

1> with

1> [

1> N=11

1> ]

1>Build log was saved at"file://f:\Boost_dev\BoostDevGuide\vs_demo\Debug\BuildLog.htm"

1>vs_demo - 1 error(s), 0 warning(s)

==========Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

(2)N = 6

4、progress_display

#include <vector>
#include <string>
#include <fstream>
#include <boost/progress.hpp>
using namespacestd;
using namespaceboost;

void progress_display_test()
{
vector<string>vs(1000,"hello");
ofstream fs("./test.txt");

progress_display pd(static_cast<unsignedlong>(vs.size()));
vector<string>::iteratoriter =vs.begin();
while (iter!=vs.end() )
{
fs<<*iter<<" ";
++pd;
++iter;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: