[BUG] TIMER on Unix/Linux issues

General FreeBASIC programming questions.
Post Reply
Jattenalle
Posts: 61
Joined: Nov 17, 2023 14:41
Contact:

[BUG] TIMER on Unix/Linux issues

Post by Jattenalle »

The internal FB code for TIMER on Unix/Linux is this (src/rtlib/unix/time_timer.c)

Code: Select all

FBCALL double fb_Timer( void )
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (((double)tv.tv_sec * 1000000.0) + (double)tv.tv_usec) * 0.000001;
}
(Note that DOS uses the exact same code found in src/rtlib/dos/time_timer.c, and may also be susceptible to this bug)

The problem is with the use of gettimeofday(), it's not monotonic and can be changed at any time for any reason including NTP or user changing the system time.

Which means a subsequent later call to TIMER can result in wildly unexpected results such as negative time having passed:

Code: Select all

t1 = TIMER
sleep 10000
'// [System clock is rewound ten seconds]
t2 = TIMER
print t2 - t1 '// Result is ~0, expected ~10
(This is code is just illustrative and not meant to represent a real-world scenario)

Expected behaviour: Subsequent calls to TIMER should never go backwards

Proposed solution: gettimeofday() is obsolete, use clock_gettime(CLOCK_MONOTONIC, ...) (https://www.man7.org/linux/man-pages/ma ... ime.3.html) instead.
Post Reply