網站首頁 編程語言 正文
標準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/archive/2013/02/05/2892504.html
相關推薦
- 2022-09-03 詳解.NET主流的幾款重量級?ORM框架_實用技巧
- 2022-12-26 matplotlib畫圖之修改坐標軸刻度問題_python
- 2022-04-18 Python裝飾器實現函數運行時間的計算_python
- 2022-07-04 反向傳播BP學習算法Gradient?Descent的推導過程_相關技巧
- 2022-05-25 kotlin將網絡上可以訪問的url圖片轉換成Base64字符串
- 2023-07-22 Redis使用教程之jedis客戶端sendCommand方法的byte[]入參,防止混淆strin
- 2022-05-18 一起來了解React的Hook_React
- 2022-05-04 詳解Python使用apscheduler定時執行任務_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支