通過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官方文檔

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM