有誰知道Windows環境中gettimeofday()函數的等價函數嗎?我正在比較Linux與Windows中的代碼執行時間。我使用MS Visual Studio 2010,它一直說,標識符「gettimeofday」未定義。Windows的gettimeday()的等價物
感謝任何指針。
有誰知道Windows環境中gettimeofday()函數的等價函數嗎?我正在比較Linux與Windows中的代碼執行時間。我使用MS Visual Studio 2010,它一直說,標識符「gettimeofday」未定義。Windows的gettimeday()的等價物
感謝任何指針。
GetLocalTime()
系統中的時區,GetSystemTime()
爲UTC時間。如果你想要一個自紀元時間,請使用SystemTimeToFileTime()
或GetSystemTimeAsFileTime()
。
對於間隔服用,使用GetTickCount()
。它從啓動後返回毫秒。
對於服用的間隔儘可能最好的分辨率(僅通過硬件的限制),使用QueryPerformanceCounter()
。
如果您確實需要使用Windows API和正確轉換的Windows gettimeofday()實現,here is one from PostgreSQL。
但是,如果你想要時間碼,我建議你看看QueryPerformanceCounter()或directly invoking the TSC,如果你只打算在x86上運行。
這裏是一個自由的實現:[?我應該用什麼來替代Windows上的gettimeofday()]的
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <stdint.h> // portable: uint64_t MSVC: __int64
// MSVC defines this in winsock2.h!?
typedef struct timeval {
long tv_sec;
long tv_usec;
} timeval;
int gettimeofday(struct timeval * tp, struct timezone * tzp)
{
// Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's
// This magic number is the number of 100 nanosecond intervals since January 1, 1601 (UTC)
// until 00:00:00 January 1, 1970
static const uint64_t EPOCH = ((uint64_t) 116444736000000000ULL);
SYSTEMTIME system_time;
FILETIME file_time;
uint64_t time;
GetSystemTime(&system_time);
SystemTimeToFileTime(&system_time, &file_time);
time = ((uint64_t)file_time.dwLowDateTime) ;
time += ((uint64_t)file_time.dwHighDateTime) << 32;
tp->tv_sec = (long) ((time - EPOCH)/10000000L);
tp->tv_usec = (long) (system_time.wMilliseconds * 1000);
return 0;
}
謝謝:) :) :) – Omeriko
非常好。我有一個包含這個實現的代碼。完全一樣的,但我需要有這個代碼在Linux上工作,我不知道該怎麼做。我將如何實現這段代碼,以使用C++或C使用相同的實現在Linux中進行編譯? Thks – S4nD3r
@ S4nD3r #ifdef _WIN32 ...包括上面的幾行... #else #include
可能重複(http://stackoverflow.com/questions/1676036/what-should-我用更換的-gettimeofday的上窗口) –