C++ 擷取時間

來源:互聯網
上載者:User

標籤:system   argc   int   cas   time_t   ++   時鐘   clu   strong   

 C++ 擷取時間

 

標頭檔 chrono, 命名空間 std.

現在時間
  std::chrono::system_clock::now() 返回系統時鐘的目前時間

 

時鐘
  std::chrono::system_clock 代表系統當前的時間, 是不穩定的時鐘, 並且提供了函數可將時間點轉化為 time_t 類型的值
  std::chrono::steady_clock 表示一個穩定的時鐘, 所謂穩定指調用 now()時, 其值總是大於上1次.

 

延遲
  std::this_thread::sleep_for() 和 std::this_thread::sleep_until()
  std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 等待 100ms

 

 1 #define _CRT_SECURE_NO_WARNINGS 2  3 #include <iostream> 4 #include <string> 5 #include <sstream> 6 #include <iomanip> 7 #include <chrono> 8  9 std::string GetTimeStr()10 {11     std::chrono::system_clock::time_point now = std::chrono::system_clock::now();12     time_t tt = std::chrono::system_clock::to_time_t(now);13     struct tm ltm = {0};14     localtime_s(&ltm, &tt);15     std::stringstream stm;16     stm << std::setfill(‘0‘);17     stm << std::setw(4) << (ltm.tm_year + 1900) << "-";18     stm << std::setw(2) << (ltm.tm_mon + 1) << "-";19     stm << std::setw(2) << (ltm.tm_mday) << " ";20     stm << std::setw(2) << (ltm.tm_hour) << "-";21     stm << std::setw(2) << (ltm.tm_min) << "-";22     stm << std::setw(2) << (ltm.tm_sec);23 24     return stm.str();25 }26 27 void mytest(void)28 {29     std::cout << "<<<<<<<<<<<<<<<<<<<<<<<<<" << std::endl;30 31     std::chrono::steady_clock::time_point tbegin = std::chrono::steady_clock::now();32     std::cout << GetTimeStr().c_str() << std::endl;33     std::chrono::steady_clock::time_point tend = std::chrono::steady_clock::now();34     std::chrono::milliseconds used = std::chrono::duration_cast<std::chrono::milliseconds>(tend - tbegin);35     std::cout << used.count() << "ms" << std::endl;36 37     std::cout << "<<<<<<<<<<<<<<<<<<<<<<<<<" << std::endl;38 }39 40 int main(int argc, char * argv[], char * envp[])41 {42     mytest();43 44     system("pause");45     return 0;46 }

 

運行結果:

 

C++ 擷取時間

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.