首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >相当于Windows的gettimeday()

相当于Windows的gettimeday()
EN

Stack Overflow用户
提问于 2012-06-06 06:28:22
回答 6查看 65.1K关注 0票数 35

有没有人知道在Windows环境下gettimeofday()函数的一个等价函数?我正在比较Linux和Windows中的代码执行时间。我正在使用MS Visual Studio2010,它一直在说,标识符"gettimeofday“是未定义的。

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2012-06-06 06:35:22

系统时区中的时间为GetLocalTime(),协调时为GetSystemTime()。它们返回SYSTEMTIME结构中的日期/时间,在那里它被解析为年、月等。如果您想要一个自纪元以来的秒数时间,可以使用SystemTimeToFileTime()GetSystemTimeAsFileTime()FILETIME是一个64位数值,自1601年1月1日起间隔为100 is。

对于间隔采集,请使用GetTickCount()。它返回自启动以来的毫秒数。

要以最佳分辨率拍摄间隔(仅受硬件限制),请使用QueryPerformanceCounter()

票数 16
EN

Stack Overflow用户

发布于 2014-09-28 22:21:20

下面是一个免费的实现:

代码语言:javascript
复制
#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;
}
票数 78
EN

Stack Overflow用户

发布于 2019-09-30 13:51:19

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

谢谢你,Howard Hinnant的建议。

代码语言:javascript
复制
#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
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10905892

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档