HELP: gettimeofday() jumps backwards

From: kindsol (kindsol_at_hotmail.com)
Date: 05/18/04


Date: Mon, 17 May 2004 18:31:56 -0700

I need a reliable counter in Linux on a x86 platform for a real-time motion
control system.

I have been attempting to use gettimeofday(), but this timer jumps forward
(by about a second) and then jumps back. This occurs very close to when
tv_usec is about to rollover.

Has this problem been fixed in later kernels? Where would I find out about
this? Is there another counter that I should use recommend.

Here is the output of my test code:

gettimeofday() = [1084450549, 965955], time() = 1084450549
gettimeofday() = [1084450549, 967902], time() = 1084450549
gettimeofday() = [1084450549, 970068], time() = 1084450549
gettimeofday() = [1084450549, 971807], time() = 1084450549
gettimeofday() = [1084450549, 973975], time() = 1084450549
gettimeofday() = [1084450549, 975718], time() = 1084450549
gettimeofday() = [1084450549, 977666], time() = 1084450549
gettimeofday() = [1084454844, 946918], time() = 1084454844 //jumps forward
here
gettimeofday() = [1084454844, 948870], time() = 1084454844
gettimeofday() = [1084454844, 951038], time() = 1084454844
gettimeofday() = [1084454844, 954282], time() = 1084454844
gettimeofday() = [1084454844, 954728], time() = 1084454844
gettimeofday() = [1084454844, 956896], time() = 1084454844
gettimeofday() = [1084454844, 958634], time() = 1084454844
gettimeofday() = [1084454844, 960587], time() = 1084454844
gettimeofday() = [1084454844, 963618], time() = 1084454844
gettimeofday() = [1084454844, 964493], time() = 1084454844
gettimeofday() = [1084454844, 966447], time() = 1084454844
gettimeofday() = [1084450550, 1105], time() = 1084450550 //jumps back
here
ERROR: clock jumped backwards!

Here is my test code:

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

int main() {
    struct timeval tod;
    long tim, timPrev=-1;
    for (;;) {
        //do {
        gettimeofday(&tod, NULL);
        //} while (tod.tv_usec > 900000);
        tim = time( NULL );
        printf( "gettimeofday() = [%lu, %lu], time() = %lu\n",
                (unsigned long) tod.tv_sec,
                (unsigned long) tod.tv_usec,
                (unsigned long) tim );
                usleep(0);

        if (timPrev>tim) {
            printf("ERROR: clock jumped backwards!\n");
            break;
            }
        timPrev = tim;
    }
}

I am currently using kernel-2.4.18-14.
Any help/direction would be much appreciated!
Thank you!!

-Sol