Update: fixed delta calculations in code, still the issue remains
Folks, could you please explain why I'm getting very strange results from time to time using the the following code:
#include <unistd.h>
#include <sys/time.h>
#include <stdio.h>
int main()
{
struct timeval start, end;
long mtime1, mtime2, diff;
while(1)
{
gettimeofday(&start, NULL);
usleep(2000);
gettimeofday(&end, NULL);
mtime1 = (start.tv_sec * 1000 + start.tv_usec/1000.0);
mtime2 = (end.tv_sec * 1000 + end.tv_usec/1000.0);
diff = mtime2 - mtime1;
if(diff > 10)
printf("WTF: %ld\n", diff);
}
return 0;
}
(You can compile and run it with: gcc test.c -o out -lrt && ./out)
What I'm experiencing is sporadic big values of diff variable almost every second or even more often, e.g:
$ gcc test.c -o out -lrt && ./out
WTF: 14
WTF: 11
WTF: 11
WTF: 11
WTF: 14
WTF: 13
WTF: 13
WTF: 11
WTF: 16
How can this be possible? Is it OS to blame? Does it do too much context switching? But my box is idle( load average: 0.02, 0.02, 0.3).
Here is my Linux kernel version:
$ uname -a
Linux kurluka 2.6.31-21-generic #59-Ubuntu SMP Wed Mar 24 07:28:56 UTC 2010 i686 GNU/Linux