2012-06-05 67 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