c++ - Windows 的 timespec 等价物

标签 c++ c windows datetime win32-process

我正在将我的应用程序从 unix 移植到 windows,但我遇到了困难。在我的应用程序中,我需要找到以微秒为单位的时间(由于它是高精度应用程序,因此整个应用程序在很大程度上依赖于它)。

以前我使用的是timespec结构,但是windows不包含这样的东西。命令 GetTickCount 不够用,因为它以毫秒为单位返回时间。我也在考虑 QueryPerformanceFrequency

有人会碰巧知道与 timespec 尽可能相同的东西吗?

将来我什至可能也需要纳秒,我在 Windows 中搜索的任何内容都不支持。

最佳答案

参见,例如,How to realise long-term high-resolution timing on windows using C++?C++ Timer function to provide time in nano seconds .

我在 Windows XP 下用 Cygwin 做了一些测试:在我的机器上,gettimeofday() 的粒度大约是 15 毫秒(~1/64 秒)。这是相当粗糙的。粒度也是如此:

* clock_t clock(void) (divisor CLOCKS_PER_SEC)
* clock_t times(struct tms *) (divisor sysconf(_SC_CLK_TCK))

两个除数都是 1000(POSIX 可能第一个是 1000000)。

此外,clock_getres(CLOCK_REALTIME,...) 返回 15 毫秒,因此 clock_gettime() 不太可能提供帮助。 CLOCK_MONOTONIC 和 CLOCK_PROCESS_CPUTIME_ID 不起作用。

Windows 的其他可能性可能是 RDTSC ;请参阅维基百科文章。和 HPET ,这在 Windows XP 中不可用。

另请注意,在 Linux 中,clock() 是进程时间,而在 Windows 中则是挂钟时间。

一些示例代码,既适用于标准 Unix,也适用于在 Windows 下运行的 CYGWIN 代码,其粒度约为 50 微秒(在我的 机器上)。返回值以秒为单位,并给出自首次调用该函数以来经过的秒数。 (我后来才意识到这是我在 a year ago 上给出的答案)。

#ifndef __CYGWIN32__
double RealElapsedTime(void) { // returns 0 seconds first time called
   static struct timeval t0;
   struct timeval tv;
   gettimeofday(&tv, 0);
   if (!t0.tv_sec)
      t0 = tv;
   return tv.tv_sec - t0.tv_sec + (tv.tv_usec - t0.tv_usec) / 1000000.;
}
#else
#include <windows.h>
double RealElapsedTime(void) { // granularity about 50 microsecs on my machine
   static LARGE_INTEGER freq, start;
   LARGE_INTEGER count;
   if (!QueryPerformanceCounter(&count))
      FatalError("QueryPerformanceCounter");
   if (!freq.QuadPart) { // one time initialization
      if (!QueryPerformanceFrequency(&freq))
         FatalError("QueryPerformanceFrequency");
      start = count;
   }
   return (double)(count.QuadPart - start.QuadPart) / freq.QuadPart;
}
#endif

关于c++ - Windows 的 timespec 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8583308/

相关文章:

c++ - 删除后立即赋值给指针

在窗口中更改 GTK 标签位置 - C

c - 如何通过 system() 使用命令行变量?

linux - 有没有办法从ubuntu复制到windows?比如我可以安装的命令或功能?

c - 一个 C 程序演示 cmd.exe 和一个 linux shell 例如bash,定界参数?

c++ - child 的祖 parent 重载功能

c++ - 我应该使用#define、枚举还是常量?

c# - Windows 7 不允许我编辑 Common Application Data 文件夹中的文件

c++ - 这些nullptr位于哪里?

c - 生成所有具有重复数字的组合