C++通過boost.date_time進(jìn)行時(shí)間運(yùn)算
標(biāo)準(zhǔn)C函數(shù)的時(shí)間運(yùn)算是非常不好用的,boost提供了一個(gè)跨平臺的日期庫boost.date_time,通過它可以快速實(shí)現(xiàn)各種時(shí)間運(yùn)算。
boost.date_time中的時(shí)間對象為boost::posix_time::ptime,在<boost/date_time.hpp>中定義,它的常用操作如下。
獲取現(xiàn)在時(shí)間:
ptime now = second_clock::local_time(); cout << now << endl;
獲取日期信息:
cout << now.date().day_of_week();
通過偏移獲取新時(shí)間:
ptime today = now - now.time_of_day(); ptime next_time = now + years(1) + months(1) + days(1) - hours(1);
計(jì)算時(shí)間差:
time_duration?timespan = now - today;
時(shí)間比較:
bool?result = next_day > now;
字符串轉(zhuǎn)換為時(shí)間
標(biāo)準(zhǔn)格式的字符串可以通過time_from_string轉(zhuǎn)換。
cout << time_from_string("2010-09-10 10:01:01");
但對于非標(biāo)準(zhǔn)的格式的時(shí)間,則需要自定義解析函數(shù)。這里我簡單的寫了一個(gè):
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");
精準(zhǔn)計(jì)時(shí)
對于一般的計(jì)時(shí)操作,可以通過前面的時(shí)間差運(yùn)算獲取。但是,有的時(shí)候需要高精度計(jì)時(shí)操作,這個(gè)時(shí)候需要用到boost的另外一個(gè)庫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; }
關(guān)于cpu_timer更多信息,請參看boost官方文檔。
到此這篇關(guān)于C++通過boost.date_time進(jìn)行時(shí)間運(yùn)算的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解C++編程中類的成員變量和成員函數(shù)的相關(guān)知識
這篇文章主要介紹了C++編程中類的成員變量和成員函數(shù)的相關(guān)知識,是C++入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-09-09C語言驅(qū)動(dòng)開發(fā)之內(nèi)核通過PEB獲取進(jìn)程參數(shù)
PEB結(jié)構(gòu)(Process Envirorment Block Structure)其中文名是進(jìn)程環(huán)境塊信息。本文將通過PEB實(shí)現(xiàn)獲取進(jìn)程參數(shù),感興趣的小伙伴可以了解一下2022-10-10