C++ 獲取時間


 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 }

 

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM