zoukankan      html  css  js  c++  java
  • 通过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官方文档

     

  • 相关阅读:
    mybatis 对string类型判断比较 group case when then 综合
    利用Apache shiro SimpleHash 加密字符串
    linux下用rpm 安装jdk
    运行java程序的时候出现Exception in thread "main" java.lang.UnsupportedClassVersionError:
    linux如何查看端口被哪个进程占用?
    Linux如何查看JDK的安装路径
    Linux中查看jdk版本
    linux修改/etc/profile权限
    db2,oracle,mysql ,sqlserver限制返回的行数
    什么是T-SQL
  • 原文地址:https://www.cnblogs.com/TianFang/p/2892504.html
Copyright © 2011-2022 走看看