1.时间处理
1.timer库
timer类
Boost 中的timer库是一个很小的库
早期的timer库:该库的计时精度低,Boost官方已经不再推荐使用(编译会有告警)
新的cpu_timer库:基于chrono库使用操作系统的API,计时精度更高
**使用:**timer接口简单,适用于大部分要求不高的程序计时任务,elapsed_min()和elapsed_max()计时的精度表明了timer的能力
timer不适用于高精度的时间测量任务,它的精度依赖于操作系统和编译器,难以做到跨平台;也不适用于测量大跨度的时间段,如果要以天,月甚至年为时间单位就不能使用timer。
#include <boost/timer.hpp>
#include <iostream>
using namespace boost;
using namespace std;
int main()
{
timer t;
cout << "max timespan:" << t.elapsed_max() / 3600 << "h" << endl; //可度量的最大时间,以小时为单位
cout << "min timespan:" << t.elapsed_min() << "s" << endl; //可度量的最小时间,以秒为单位
cout << "now time elapsed:" << t.elapsed() << "s" << endl; //输出从对象创建到现在的时间
return 0;
}
timer类的源码
#ifndef BOOST_TIMER_HPP
#define BOOST_TIMER_HPP
#include <boost/config.hpp>
#include <ctime>
#include <boost/limits.hpp>
# ifdef BOOST_NO_STDC_NAMESPACE
namespace std { using ::clock_t; using ::clock; }
# endif
namespace boost {
class timer
{
public:
timer() { _start_time = std::clock(); }
void restart() { _start_time = std::clock(); }
double elapsed() const
{ return double(std::clock() - _start_time) / CLOCKS_PER_SEC; }
double elapsed_max() const
{
return (double((std::numeric_limits<std::clock_t>::max)())
- double(_start_time)) / double(CLOCKS_PER_SEC);
}
double elapsed_min() const
{ return double(1)/double(CLOCKS_PER_SEC); } //#define CLOCKS_PER_SEC ((clock_t)1000)
private:
std::clock_t _start_time;
};
}
#endif // BOOST_TIMER_HPP
progress_timer类
是一个定时器,继承了timer的全部功能,会在析构时自动输出时间,省去手动调用elapsed()函数的工作,是一个相当方便的自动计时小工具
使用
#include <boost/progress.hpp>
#include <windows.h>
#include <iostream>
using namespace boost;
using namespace std;
int main()
{
progress_timer t;
return 0;
}
progress_timer类的源码
#ifndef BOOST_PROGRESS_HPP
#define BOOST_PROGRESS_HPP
#include <boost/timer.hpp>
#include <boost/noncopyable.hpp>
#include <boost/cstdint.hpp> // for uintmax_t
#include <iostream> // for ostream, cout, etc
#include <string> // for string
namespace boost {
class progress_timer : public timer, private noncopyable
{
public:
explicit progress_timer( std::ostream & os = std::cout )//允许将析构时的输出定向到指定的输入输出流里
: timer(), noncopyable(), m_os(os) {}
~progress_timer()
{
try
{
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 (...) {}
} // ~progress_timer
private:
std::ostream & m_os;
};