开发者

Is there a way to measure time up to micro seconds using C standard library?

Is there a platform-independent way to measure time up to micro seconds using C standard开发者_JS百科 library?


The precision of the measurement depends on the operating system, unfortunately.


While the above answers are certainly correct (c'est la vie), they are not very helpful.

I have done some testing with Cygwin under Windows XP: on my machine, the granularity of gettimeofday() is about 15 msecs (1/64 secs?). Which is big. And so is the granularity of:

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

Both divisors are 1000 (Does POSIX has 1000000 for first?).

Also, clock_getres(CLOCK_REALTIME,...) returns 15 msecs, so clock_gettime() is unlikely to help. And CLOCK_MONOTONIC and CLOCK_PROCESS_CPUTIME_ID don't work.

Other possibilites for CYGWIN might be RDTSC; see the Wikipedia article. And maybe HPET, but it isn't available with Windows XP.

Also note in Linux, clock() is the process time, while in Windows it is the wall time.

So some sample code, both for standard Unix, and for CYGWIN code running under Windows, which gives a granularity of about 50 microsecs (on my machine):

#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


The POSIX gettimeofday and clock_gettime functions are the closest thing you'll find to platform-independence. Ideally all platforms would follow POSIX, but one notable infamous one (along with various obscure ones) doesn't.


I'd use a combination of clock() and CLOCKS_PER_SEC


time() is standard for practically all C runtime libraries, but has only 1.0 second resolution. In C++ there are the BOOST ptime microsec_clock::universal_time() and ptime microsec_clock::local_time() functions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜