我正在将我的应用程序从 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/