1

Is there any way to check the granularity of gettimeofday() function provided by POSIX?

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
nikhil
  • 9,023
  • 22
  • 55
  • 81
  • I'm unclear about your question: per standard the resolution is in microseconds - "The gettimeofday() function shall obtain the current time, expressed as seconds and microseconds since the Epoch" Are you asking whether there's a programmatic way of checking that the resolution of the system clock is less than a microsecond? – RomanK Jan 23 '11 at 19:59
  • 1
    @RomanK: Resolution and granularity aren't the same thing. POSIX indeed specifies microseconds, but on a given implementation those microseconds might only increment by, for example, 1000 at a time. – caf Jan 23 '11 at 21:41

3 Answers3

3

Instead of gettimeofday(), consider using clock_gettime() (specifying the CLOCK_REALTIME clock). This is also POSIX, and supports a clock_getres() function to obtain the resolution.

caf
  • 233,326
  • 40
  • 323
  • 462
  • But `clock_getres` always return 1 ns for hrtimers instead of real timer resolution.... – osgx Apr 23 '14 at 19:30
1

Call it in a tight loop, note the difference between the current value and the previous one when it changes. Something like the following:

#include <stdio.h>
#include <sys/time.h>

int main()
{
        struct timeval timevals[2];
        int cur = 0;
        while (1) {
                gettimeofday(&timevals[cur], NULL);
                int diff = timevals[cur].tv_usec - timevals[!cur].tv_usec;
                if (diff)
                        printf("%d\n", diff);
                cur = !cur;
        }
}

On my system it seems the granularity is around 2 usec (about 50/50 one or two microseconds, with outliers in the hundreds or thousands that are likely due to task switching).

Jakob Borg
  • 23,685
  • 6
  • 47
  • 47
  • You are over-estimating the delay because you are counting the time taken to format the difference too. You should call `gettimeofday(&timevals[!cur], NULL);` immediately after the `cur = !cur;` line so that the gap between calls is minimized. You will likely find that the result is most often zero - because your machine is fast enough to make two `gettimeofday()` calls in a single microsecond. Don't forget, a microsecond is 3000 clock cycles if your CPU runs at 3 GHz; you can do quite a lot in 3000 clock cycles. – Jonathan Leffler Jan 23 '11 at 23:24
-1

The current posix way to get the resolution of gettimeofday() is

#include <unistd.h>
long ticks_per_sec = sysconf(_SC_CLK_TCK);

In older posix versions (not sure when the change happened), the value CLOCKS_PER_SEC was #defined.

user510306
  • 415
  • 3
  • 6