首页 > 代码库 > c++ boost库学习一:时间和日期
c++ boost库学习一:时间和日期
timer类
#include <boost\timer.hpp>#include "iostream"using namespace std;int _tmain(int argc, _TCHAR* argv[]){ boost::timer t; cout<<"max time span: "<<t.elapsed_max()/3600<<"h"<<endl; //596.523h cout<<"min time span: "<<t.elapsed_min()<<"s"<<endl; //0.001s cout<<"now time: "<<t.elapsed()<<"s"<<endl; //0.00s return 0;}
timer对象在创建的时候就开始计时了,它最多只能计时596个小时左右,所以适合以月、年为单位计时需求。
progress_timer类
#include "iostream"#include <boost\progress.hpp>using namespace std;int _tmain(int argc, _TCHAR* argv[]){ boost::progress_timer t; //do something; return 0;}
progress_timer 继承自timer类,progress_timer比较牛的点是它在析构的时候会自动向标准流(默认是std:out)输出自对象创建后流逝的时间;但是也可以把时间输出到其他库标准流(比如stringstream)
int _tmain(int argc, _TCHAR* argv[]){ stringstream ss; { boost::progress_timer t(ss); //do something; } cout<<ss.str(); return 0;}
progress_display类
#include "iostream"#include <Windows.h>#include <boost\progress.hpp>using namespace std;int _tmain(int argc, _TCHAR* argv[]){ //声明一个progress_display的对象,基数是一个整数 boost::progress_display p(100); int i=0; while(i<100) { i++; Sleep(1000); ++p; } return 0;}
progress_display类与timer和progress_timer没有任何关系。
它接受一个long型参数expected_count,表示用于进度显示的参数;当进度达到expected_count时表示任务已经了,进度是100%。
输出结果:
0% 10 20 30 40 50 60 70 80 90 100%
|----|----|----|----|----|----|----|----|----|----|
***********************
date类
date类是date_time库中的一个类。下面是它的几种用法。
个人觉得其中的day_of_year() 函数还是挺实用的,我就经常要算今天是第几天
#include "iostream"#include <boost\date_time\gregorian\gregorian.hpp>using namespace std;using namespace boost::gregorian;int _tmain(int argc, _TCHAR* argv[]){ /*日期的初始化*/ date d; date d2(2014,7,20); date d3 = from_string("2014-07-30"); date d4 = from_string("2014/07/30"); /*日期的获得*/ cout<<d3.year()<<"-"<<d3.month()<<"-"<<d3.day()<<endl; cout<<day_clock::local_day()<<endl; //local time cout<<day_clock::universal_day()<<endl; //UTC time cout<<d3.day_of_week()<<endl;//返回星期数,0表示星期天 cout<<d3.day_of_year()<<endl;//返回该年第几天 /*日期转换成字符串*/ cout<<to_simple_string(d3)<<endl //2014-JUL-30 cout<<to_iso_string(d3)<<endl; //20140730 cout<<to_iso_extended_string(d3)<<endl; //2014-07-30 return 0;}
c语言里有一个结构体tm可以用来处理日期,下面是date类的运算以及与tm相互转换的例子:
int _tmain(int argc, _TCHAR* argv[]){ /*日期的初始化*/ date d(2014,7,20); tm t=to_tm(d);//从date转换到tm cout<<t.tm_year<<"-"<<t.tm_mon<<"-"<<t.tm_mday<<endl; //114-6-20 (tm 是从1900年开始的,month的0代表1月) date d2=date_from_tm(t);//从tm转换到date /*日期的运算*/ date d3(2014,8,15); cout<<d3-d<<endl; cout<<d+days(10)<<endl; //2014-Jul-30 cout<<d+months(10)<<endl; //2015-May-20 cout<<d+years(10)<<endl; //2024-Jul-20 cout<<d-weeks(20)<<endl; //2014-Mar-02 return 0;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。