我試圖獲得自1970年1月1日起使用this以來的毫秒數。然而,當我嘗試編譯,我得到C++檢索自1970年1月以來的毫秒數1970年:無法打開源文件sys/time.h
"Error: cannot open source file 'sys/time.h'"
我使用Visual Studio。
我試圖獲得自1970年1月1日起使用this以來的毫秒數。然而,當我嘗試編譯,我得到C++檢索自1970年1月以來的毫秒數1970年:無法打開源文件sys/time.h
"Error: cannot open source file 'sys/time.h'"
我使用Visual Studio。
如果您正在使用C++ 11,可以使用std::chrono
。
#include <chrono>
long long GetUnixTimeChrono()
{
auto timeSinceEpoch = std::chrono::system_clock::now().time_since_epoch();
return std::chrono::duration_cast<std::chrono::milliseconds>(timeSinceEpoch).count();
}
否則,你可以這樣做:
#include <Windows.h>
long long GetUnixTime()
{
SYSTEMTIME sysUnixEpoch;
sysUnixEpoch.wYear = 1970;
sysUnixEpoch.wMonth = 1;
sysUnixEpoch.wDayOfWeek = 4;
sysUnixEpoch.wDay = 1;
sysUnixEpoch.wHour = 0;
sysUnixEpoch.wMinute = 0;
sysUnixEpoch.wSecond = 0;
sysUnixEpoch.wMilliseconds = 0;
FILETIME unixEpoch;
SystemTimeToFileTime(&sysUnixEpoch, &unixEpoch);
ULARGE_INTEGER unixEpochValue;
unixEpochValue.HighPart = unixEpoch.dwHighDateTime;
unixEpochValue.LowPart = unixEpoch.dwLowDateTime;
FILETIME systemTime;
GetSystemTimeAsFileTime(&systemTime);
ULARGE_INTEGER systemTimeValue;
systemTimeValue.HighPart = systemTime.dwHighDateTime;
systemTimeValue.LowPart = systemTime.dwLowDateTime;
long long diffHundredNanos = systemTimeValue.QuadPart - unixEpochValue.QuadPart;
return diffHundredNanos/10000;
}
sys/time.h
頭是一個POSIX頭,因此通常不在Windows機器上找到,當然也不在Windows SDK中。對於Visual Studio,您需要包含time.h
而不是sys/time.h
,如documentation中所述。
但是,Visual Studio time.h
中的函數不能提供毫秒的精度。沒有gettimeofday()
。你可以做的最好的是幾秒鐘內的Unix時間。現在,Windows上毫秒精度的Unix時間是這個問題的主題:How can i get UTCTime in millisecond since January 1, 1970 in c language。但是,接受的答案是可怕的,真的應該刪除。
經過多一點區別,我想你會在這裏找到你需要的:Convert Windows Filetime to second in Unix/Linux。工作流程如下:
GetSystemTime()
獲取系統時間。SystemTimeToFileTime
轉換爲文件時間。我覺得這是你所需要的,但要記住,我不是在C++遠程流暢:
#include <windows.h>
long long GetUnixTime()
{
const long long WINDOWS_TICK = 10000000LL;
const long long SEC_TO_UNIX_EPOCH = 11644473600LL;
SYSTEMTIME st;
GetSystemTime(&st);
FILETIME ft;
if (!SystemTimeToFileTime(&st, &ft))
return -1;
ULARGE_INTEGER uli;
uli.LowPart = ft.dwLowDateTime;
uli.HighPart = ft.dwHighDateTime;
return uli.QuadPart/WINDOWS_TICK - SEC_TO_UNIX_EPOCH;
}
這仍然沒有解決問題,因爲的gettimeofday()現在不承認(我在我提供的鏈接解決方案逐字複製) 。 – HXSP1947
解決你的問題和回答你的問題是有區別的。無論如何,我認爲我提供的最終環節應該有所斬獲。 –
不要附加wMilliseconds!它們已經計入上面的代碼中。 –