I'm having a very strange issue. I'm using gettimeofday
to control timeouts in an I/O library. I have isolated the problem that a second call to gettimeofday
returns a earlier time than first.
I've done a simple test demo that reveals the problem. It only happens in a virtualized machine (virtualbox) that runs Ubuntu 18.04.1 LTS.
#include <unistd.h>
#include <stdio.h>
#include <sys/time.h>
unsigned long GetTickCount()
{
struct timeval start, end;
unsigned long myTickCount;
gettimeofday(&start, NULL);
myTickCount =start.tv_sec*1000+start.tv_usec/1000;
return myTickCount;
}
main()
{
unsigned long a,b;
while(1) {
a=GetTickCount();
usleep(100000);
b=GetTickCount();
if(a>b)
printf("a: %ld, b:%ld, b-a=%ld\r\n",a,b,b-a);
}
}
When I run the code I get things like:
a: 1540980716756, b:1540980716090, b-a=-666
a: 1540980748208, b:1540980747542, b-a=-666
a: 1540980779740, b:1540980779074, b-a=-666
a: 1540980811180, b:1540980810513, b-a=-667
a: 1540980842713, b:1540980842047, b-a=-666
a: 1540980874153, b:1540980873487, b-a=-666
If you check it carefully you will see that the glitch is every 31.5s.
Some hint about what's happening? Is it a kind of clock drift adjusted by virtualbox?