Boost库时间日期学习

学习内容见《Boost程序库完全开发指南》第2章 时间与日期

学习三个类的使用timer、progress_timer、date。

Boost库的配置可参照:http://blog.csdn.net/segen_jaa/article/details/7407404

开发环境:WinXP+VS2005+ boost_1_49_0。
以下所有示例程序均为控制台程序。


1、timer类
timer类是一个小型的计时器,提供毫秒级别的计时精度。

#include "stdafx.h"
#include <iostream>
#include <boost/timer.hpp>

using namespace std;
using namespace boost;

int _tmain(int argc, _TCHAR* argv[])
{
    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;
}

输出结果:
max timespan:596.523h
min timespan:0.001s
now time elapsed:0.015s

2、progress_timer类
progress_timer类对timer类做了优化,在析构函数中自动输出流逝时间。

#include "stdafx.h"
#include <boost/progress.hpp>

using namespace boost;

int _tmain(int argc, _TCHAR* argv[])
{
    //progress_timer析构时会自动输出流逝时间

    {
        progress_timer t;

        //do something...
        int nSum = 0;
        for (int i = 1; i <= 1000; i++)
        {
            nSum += i;
        }
    }

    {
        progress_timer t;

        //do something...
        int nSum = 0;
        for (int i = 1; i <= 1000; i++)
        {
            nSum += i;
        }
    }

    return 0;
}

3、date类
date类使用32位的整数作为内部存储,以天为基本单位。使用date日期运算更加方便。


一周前、三月前、一年前日期确定,采用date来计算。
原先算法见: http://blog.csdn.net/segen_jaa/article/details/6821064

#include "stdafx.h"
#include <iostream>
#include <boost/date_time/gregorian/gregorian.hpp>

using namespace std;
using namespace boost::gregorian;

int _tmain(int argc, _TCHAR* argv[])
{
    date d1(2000,1,1);
    date d2(2008,8,8);

    //输出相差多少天
    cout<<(d2-d1)<<endl;

    date d3(2012,6,30);

    //一周前日期
    date d4 = d3 - days(7);
    cout<<to_iso_extended_string(d4)<<endl;

    //三个月前日期
    date d5 = d3 - months(3);
    cout<<to_iso_extended_string(d5)<<endl;

    //一年前日期
    date d6 = d3 - years(1);
    cout<<to_iso_extended_string(d6)<<endl;

    return 0;
}

输出结果如下:
3142
2012-06-23
2012-03-31
2011-06-30

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值