相当于Windows的gettimeday()

Ben*_*nny 23 winapi visual-studio-2010

有没有人知道Windows环境中gettimeofday()函数的等效函数?我正在比较Linux与Windows中的代码执行时间.我正在使用MS Visual Studio 2010并且它一直说,标识符"gettimeofday"未定义.

感谢任何指针.

Mic*_*007 64

这是一个免费的实现:

#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;
}
Run Code Online (Sandbox Code Playgroud)

  • @S4nD3r #ifdef _WIN32 ...包括上面的行... #else #include &lt;sys/time.h&gt; #endif ... 查看我在我的Buddhabrot 项目中的用法:https://raw.githubusercontent.com/Michaelangel007/ buddhabrot/master/buddhabrot.cpp (2认同)

Sev*_*yev 11

GetLocalTime()对于GetSystemTime()UTC ,系统时区的时间.如果您想要从秒开始的时间,请使用SystemTimeToFileTime()GetSystemTimeAsFileTime().

对于间歇服用,请使用GetTickCount().它返回自启动以来的毫秒数.

要获得具有最佳分辨率的间隔(仅限硬件限制),请使用QueryPerformanceCounter().


lil*_*cpp 5

这是使用chrono的 c++11 版本。

谢谢你,霍华德·辛南特的建议。

#if defined(_WIN32)
#include <chrono>

int gettimeofday(struct timeval* tp, struct timezone* tzp) {
  namespace sc = std::chrono;
  sc::system_clock::duration d = sc::system_clock::now().time_since_epoch();
  sc::seconds s = sc::duration_cast<sc::seconds>(d);
  tp->tv_sec = s.count();
  tp->tv_usec = sc::duration_cast<sc::microseconds>(d - s).count();

  return 0;
}

#endif // _WIN32
Run Code Online (Sandbox Code Playgroud)

  • 请不要简单地发布代码,解释一下它的作用以及它如何解决OP问题。 (3认同)