如何在 C++ 中以毫秒為單位獲取時間
-
使用
std::chrono::system_clock::now()方法在 C++ 中獲取以毫秒為單位的時間 -
使用
gettimeofday()函式在 C++ 中獲得以毫秒為單位的時間 -
C++ 中使用
time()函式獲取時間(毫秒)
本文將介紹多種 C++ 方法,介紹如何以毫秒為單位獲取時間。
使用 std::chrono::system_clock::now() 方法在 C++ 中獲取以毫秒為單位的時間
std::chrono::system_clock 類是 C++ 中獲取全系統實時掛鐘的介面。大多數系統使用 Unix 時間,它表示為從 1970 年 1 月 1 日 00:00:00 UTC 開始的秒數,稱為 Unix 紀元。請注意,閏秒被忽略了。因此 Unix 時間並不是 UTC 的真正準確表示。
首先,呼叫 now() 方法來返回當前的時間點。接下來呼叫的方法是 time_since_epoch 來檢索*this 和時鐘的紀元之間的時間量,但它返回的是一個 std::chrono::duration 類物件。這個物件應該呼叫 count 方法來返回實際的 ticks 數,並以毫秒來表示。結果使用 duration_cast<milliseconds> 進行投射。
#include <sys/time.h>
#include <chrono>
#include <ctime>
#include <iostream>
using std::cout;
using std::endl;
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using std::chrono::seconds;
using std::chrono::system_clock;
int main() {
auto millisec_since_epoch =
duration_cast<milliseconds>(system_clock::now().time_since_epoch())
.count();
auto sec_since_epoch =
duration_cast<seconds>(system_clock::now().time_since_epoch()).count();
cout << "seconds since epoch: " << sec_since_epoch << endl;
cout << "milliseconds since epoch: " << millisec_since_epoch << endl;
return EXIT_SUCCESS;
}
輸出:
seconds since epoch: 1603612778
milliseconds since epoch: 1603612778389
使用 gettimeofday() 函式在 C++ 中獲得以毫秒為單位的時間
gettimeofday 是符合 POSIX 標準的函式,用於檢索系統時鐘。它以 struct timeval 物件的地址作為第一個引數來儲存時間值。值是 tv_sec 代表秒數,tv_usec 代表 Unix 紀元以來的微秒數。gettimeofday 返回 int 值 0 表示成功,-1 表示失敗,提供錯誤處理功能。函式的第二個引數是 struct timezone,但是由於它已經被貶值了,你應該只傳遞一個 nullptr。注意,你需要在函式定義中加入 <sys/time.h> 標頭檔案。
#include <sys/time.h>
#include <chrono>
#include <ctime>
#include <iostream>
using std::cout;
using std::endl;
int main() {
struct timeval time_now {};
gettimeofday(&time_now, nullptr);
time_t msecs_time = (time_now.tv_sec * 1000) + (time_now.tv_usec / 1000);
cout << "seconds since epoch: " << time_now.tv_sec << endl;
cout << "milliseconds since epoch: " << msecs_time << endl << endl;
return EXIT_SUCCESS;
}
輸出:
seconds since epoch: 1603612778
milliseconds since epoch: 1603612778389
C++ 中使用 time() 函式獲取時間(毫秒)
在 C++ 中,另一種符合 POSIX 標準的檢索系統時間的方法是呼叫 time 函式。time 接受一個型別為 time_t*的可選引數,返回的時間值就儲存在這個引數中。另外,也可以使用函式返回值儲存在單獨宣告的變數中。在後一種情況下,可以傳遞 nullptr 作為引數。注意,這個呼叫並沒有像前面的呼叫那樣以同樣的精度返回時間。
#include <sys/time.h>
#include <chrono>
#include <ctime>
#include <iostream>
using std::cout;
using std::endl;
int main() {
time_t now = time(nullptr);
time_t mnow = now * 1000;
cout << "seconds since epoch: " << now << endl;
cout << "milliseconds since epoch: " << mnow << endl << endl;
return EXIT_SUCCESS;
}
輸出:
seconds since epoch: 1603612778
milliseconds since epoch: 1603612778000
