How do I measure time in C?

Viewed 81932

I want to find out for how long (approximately) some block of code executes. Something like this:

startStopwatch();
// do some calculations
stopStopwatch();
printf("%lf", timeMesuredInSeconds);

How?

8 Answers

The standard C library provides the time function and it is useful if you only need to compare seconds. If you need millisecond precision, though, the most portable way is to call timespec_get. It can tell time up to nanosecond precision, if the system supports. Calling it, however, takes a bit more effort because it involves a struct. Here's a function that just converts the struct to a simple 64-bit integer.

#include <stdio.h>
#include <inttypes.h>
#include <time.h>

int64_t millis()
{
    struct timespec now;
    timespec_get(&now, TIME_UTC);
    return ((int64_t) now.tv_sec) * 1000 + ((int64_t) now.tv_nsec) / 1000000;
}

int main(void)
{
    printf("Unix timestamp with millisecond precision: %" PRId64 "\n", millis());
}

Unlike clock, this function returns a Unix timestamp so it will correctly account for the time spent in blocking functions, such as sleep. This is a useful property for benchmarking and implementing delays that take running time into account.

For sake of completeness, there is more precise clock counter than GetTickCount() or clock() which gives you only 32-bit result that can overflow relatively quickly. It's QueryPerformanceCounter(). QueryPerformanceFrequency() gets clock frequency which is a divisor for two counters difference. Something like CLOCKS_PER_SEC in <time.h>.

#include <stdio.h>
#include <windows.h>

int main()
    {
    LARGE_INTEGER tu_freq, tu_start, tu_end;
    __int64 t_ns;

    QueryPerformanceFrequency(&tu_freq);
    QueryPerformanceCounter(&tu_start);
    /* do your stuff */
    QueryPerformanceCounter(&tu_end);

    t_ns = 1000000000ULL * (tu_end.QuadPart - tu_start.QuadPart) / tu_freq.QuadPart;
    printf("dt = %g[s]; (%llu)[ns]\n", t_ns/(double)1e+9, t_ns);

    return 0;
    }
Related