Small microsecond offset with recurent calls to gettimeofday
17:42 04 Jul 2026

I have created a small function which goal is to print the time every 2 seconds, below the main

#include 
#include 
#include 
#include 

typedef struct timeval t_time;

int main(void)
{
    t_time          *time;
    long long   check_tm;
    long long   tm;

    time = malloc(sizeof(t_time));
    check_tm = 0;
    while (1)
    {
        gettimeofday(time, NULL);
        tm = time->tv_sec * 1000000 + time->tv_usec;
        printf("time is : %lld\n", tm);
        while (((tm - check_tm) * -1) < 2000000)
        {
            gettimeofday(time, NULL);
            check_tm = time->tv_sec * 1000000 + time->tv_usec;
        }
    }
    return (0);
}

/*int main(void)
{
    t_time          *time;
    unsigned long   tm;

    time = malloc(sizeof(t_time));
    while (1)
    {
        gettimeofday(time, NULL);
        tm = time->tv_sec * 1000000 + time->tv_usec;
        printf("time is : %lu\n", tm);
        usleep(2000000);
    }
    return (0);
}*/

Notice the commented out main which does the same with usleep, this one is not accurate enough for my needs.

When I compile and launch the a.out, I have a satisfying but strange result :

Sometimes, a small offset (only of a few microseconds) occurs.

time is : 1783199478685053

...

(prints correct result of + 2secs tens of time)

...

time is : 1783199680685064

...

(prints correct result of + 2secs tens of time)

...

time is : 1783199968685068

Why?

c time gettimeofday