C++11新特性,利用std::chrono精简传统获取系统时间的方法
生活随笔
收集整理的這篇文章主要介紹了
C++11新特性,利用std::chrono精简传统获取系统时间的方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、傳統的獲取系統時間的方法
傳統的C++獲取時間的方法須要分平臺來定義。
相信百度代碼也不少。
我自己寫了下,例如以下。
const std::string getCurrentSystemTime() {if (PLATFORM_ANDROID || PLATFORM_IOS){struct timeval s_now;struct tm* p_tm;gettimeofday(&s_now,NULL);p_tm = localtime((const time_t*)&s_now.tv_sec);char date[60] = {0};sprintf(date, "%d-%02d-%02d %02d:%02d:%02d",(int)p_tm->tm_year + 1900,(int)p_tm->tm_mon + 1,(int)p_tm->tm_mday,(int)p_tm->tm_hour,(int)p_tm->tm_min,(int)p_tm->tm_sec);return std::string(date);}if (PLATFORM_W32){struct tm* p_tm;time_t timep;time(&timep);p_tm = localtime(&timep);char date[60] = {0};sprintf(date, "%d-%02d-%02d %02d:%02d:%02d",(int)p_tm->tm_year + 1900,(int)p_tm->tm_mon + 1,(int)p_tm->tm_mday,(int)p_tm->tm_hour,(int)p_tm->tm_min,(int)p_tm->tm_sec);log("%s",date);return std::string(date);}return ""; }二、C++11 std標準庫跨平臺方法
顯然,我們注意到不同平臺下的代碼相似度非常高。那么能不能利用C++11里面的新特性,使得二者合并呢?答案是肯定的。
非常easy的。代碼例如以下:
const std::string getCurrentSystemTime() {auto tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());struct tm* ptm = localtime(&tt);char date[60] = {0};sprintf(date, "%d-%02d-%02d %02d:%02d:%02d",(int)ptm->tm_year + 1900,(int)ptm->tm_mon + 1,(int)ptm->tm_mday,(int)ptm->tm_hour,(int)ptm->tm_min,(int)ptm->tm_sec);return std::string(date); }又短又簡單有木有。
本文原創,如需轉載,請說明出處:
http://blog.csdn.net/q229827701/article/details/41015483
轉載于:https://www.cnblogs.com/yxwkf/p/5364805.html
總結
以上是生活随笔為你收集整理的C++11新特性,利用std::chrono精简传统获取系统时间的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VBA与Excel内置的函数
- 下一篇: struts 的 MVC ,自己堆栈跟踪