網站首頁 編程語言 正文
標準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
相關推薦
- 2023-04-10 基于Python實現錄音功能的示例代碼_python
- 2022-01-30 uniapp history路由配置,apache服務器簡單配置(刷新報404解決方法)
- 2023-07-22 linux自動化運維之linux腳本自動操作redis數據
- 2022-08-02 C#?HttpClient?Post參數同時上傳文件的實現_C#教程
- 2022-09-09 python中.format()方法使用詳解_python
- 2022-06-30 python神經網絡tensorflow利用訓練好的模型進行預測_python
- 2022-01-22 記一次線上sql優化從9s到400ms的過程
- 2022-10-30 移動web開發技能之touch事件詳解_IOS
- 最近更新
-
- 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同步修改后的遠程分支