有没有人知道在Windows环境下gettimeofday()
函数的一个等价函数?我正在比较Linux和Windows中的代码执行时间。我正在使用MS Visual Studio2010,它一直在说,标识符"gettimeofday“是未定义的。
发布于 2012-06-06 06:35:22
系统时区中的时间为GetLocalTime()
,协调时为GetSystemTime()
。它们返回SYSTEMTIME
结构中的日期/时间,在那里它被解析为年、月等。如果您想要一个自纪元以来的秒数时间,可以使用SystemTimeToFileTime()
或GetSystemTimeAsFileTime()
。FILETIME
是一个64位数值,自1601年1月1日起间隔为100 is。
对于间隔采集,请使用GetTickCount()
。它返回自启动以来的毫秒数。
要以最佳分辨率拍摄间隔(仅受硬件限制),请使用QueryPerformanceCounter()
。
发布于 2014-09-28 22:21:20
下面是一个免费的实现:
#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;
}
发布于 2019-09-30 13:51:19
这是使用chrono的c++11版本。
谢谢你,Howard Hinnant的建议。
#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
https://stackoverflow.com/questions/10905892
复制相似问题