通过boost.date_time进行时间运算

标准C函数的时间运算是非常不好用的,boost提供了一个跨平台的日期库boost.date_time,通过它可以快速实现各种时间运算。

boost.date_time中的时间对象为boost::posix_time::ptime,在<boost/date_time.hpp>中定义,它的常用操作如下。

获取现在时间:

    ptime now = second_clock::local_time();
    cout << now << endl;

获取日期信息:

    cout << now.date().day_of_week();

通过偏移获取新时间:

    ptime today = now - now.time_of_day();
    ptime next_time = now + years(1) + months(1) + days(1) - hours(1);

计算时间差:

    time_duration timespan = now - today;

时间比较:

    bool result = next_day > now;

字符串转换为时间

标准格式的字符串可以通过time_from_string转换。

    cout << time_from_string("2010-09-10 10:01:01");

但对于非标准的格式的时间,则需要自定义解析函数。这里我简单的写了一个:

ptime time_parse_exact(const string& time_str, const string& format)
    {
        ptime output;
        time_input_facet facet1(format, 1);

        std::stringstream ss1(time_str);
        ss1.imbue(std::locale(ss1.getloc(), &facet1));
        ss1 >> output;

        return output;
    }
    cout << time_parse_exact("2010/09/10-10:01:01", "%Y/%m/%d-%H:%M:%S");

精准计时

对于一般的计时操作,可以通过前面的时间差运算获取。但是,有的时候需要高精度计时操作,这个时候需要用到boost的另外一个库cpu_timer。

    #include <boost/timer/timer.hpp>
    int main(void)
    {
        boost::timer::cpu_timer timer;
        for (long i = 0; i < 100000000; ++i)
            std::sqrt(123.456L);

        cout << timer.format() << endl;
        //std::cout << timer.format(5, "%ws wall time,%ts totle time\n");

        return 0;
    }

关于cpu_timer更多信息,清参看boost官方文档

 

原文地址:https://www.cnblogs.com/TianFang/p/2892504.html