2012-06-05 65 views
17

有誰知道Windows環境中gettimeofday()函數的等價函數嗎?我正在比較Linux與Windows中的代碼執行時間。我使用MS Visual Studio 2010,它一直說,標識符「gettimeofday」未定義。Windows的gettimeday()的等價物

感謝任何指針。

+2

可能重複(http://stackoverflow.com/questions/1676036/what-should-我用更換的-gettimeofday的上窗口) –

回答

8

GetLocalTime()系統中的時區,GetSystemTime()爲UTC時間。如果你想要一個自紀元時間,請使用SystemTimeToFileTime()GetSystemTimeAsFileTime()

對於間隔服用,使用GetTickCount()。它從啓動後返回毫秒。

對於服用的間隔儘可能最好的分辨率(僅通過硬件的限制),使用QueryPerformanceCounter()

54

這裏是一個自由的實現:[?我應該用什麼來替代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; 
} 
+0

謝謝:) :) :) – Omeriko

+0

非常好。我有一個包含這個實現的代碼。完全一樣的,但我需要有這個代碼在Linux上工作,我不知道該怎麼做。我將如何實現這段代碼,以使用C++或C使用相同的實現在Linux中進行編譯? Thks – S4nD3r

+0

@ S4nD3r #ifdef _WIN32 ...包括上面的幾行... #else #include #endif ...查看我對我的Buddhabrot項目的用法:https://raw.githubusercontent.com/Michaelangel007/buddhabrot/master /buddhabrot.cpp – Michaelangel007