標准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官方文檔。