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

后端 未结 5 682
旧时难觅i
旧时难觅i 2021-01-22 03:33

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

相关标签:
5条回答
  • 2021-01-22 04:04

    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.

    0 讨论(0)
  • 2021-01-22 04:11

    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
    
    0 讨论(0)
  • 2021-01-22 04:21

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

    0 讨论(0)
  • 2021-01-22 04:23

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

    0 讨论(0)
  • 2021-01-22 04:27

    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 讨论(0)
提交回复
热议问题