是否有一种使用C标准库来测量时间至微秒的platform-independent方法?
发布于 2010-12-05 17:29:27
不幸的是,测量的精度取决于操作系统。
发布于 2010-12-05 23:54:30
虽然上面的答案肯定是正确的(c‘’est la vie),但它们并没有多大帮助。
我在Windows下用Cygwin做了一些测试:在我的机器上,gettimeofday()的粒度大约是15 msecs (1/64 secs?)。它很大。以下方面的粒度也是如此:
这两个除数都是1,000( POSIX第一项有1000000吗?)
还有,clock_getres(CLOCK_REALTIME,.)返回15个msecs,因此clock_gettime()不太可能有所帮助。CLOCK_MONOTONIC和CLOCK_PROCESS_CPUTIME_ID不起作用。
其他可能用于CYGWIN的可能是RDTSC;请参阅Wikipedia的文章。也许是HPET,但Windows是无法提供的。
还请注意,在Linux中,clock()是进程时间,而在Windows中是墙时间。
因此,一些示例代码,既适用于标准Unix,也适用于在Windows下运行的CYGWIN代码,这给出了大约50微秒的粒度(在我的机器上):
#if !CYGWIN
double realElapsedTime(void) { // returns 0 first time called
static struct timeval t0;
struct timeval tv;
gettimeofday(&tv, 0);
if (!t0.tv_sec) // one time initialization
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
static LARGE_INTEGER freq, start;
LARGE_INTEGER count;
if (!QueryPerformanceCounter(&count))
assert(0 && "QueryPerformanceCounter");
if (!freq.QuadPart) { // one time initialization
if (!QueryPerformanceFrequency(&freq))
assert(0 && "QueryPerformanceFrequency");
start = count;
}
return (double)(count.QuadPart - start.QuadPart) / freq.QuadPart;
}
#endif发布于 2010-12-05 17:43:52
POSIX、gettimeofday和clock_gettime函数是与平台无关的最接近的东西。理想情况下,所有平台都会遵循POSIX,但一个臭名昭著的平台(以及各种晦涩的平台)则不会。
https://stackoverflow.com/questions/4360073
复制相似问题