Is there any way to 开发者_高级运维check the granularity of gettimeofday() function provided by POSIX?
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.
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).
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.
精彩评论