c++cdifftimetimeval

How is it possible that tv_sec of both timeval structures are the same but subtracting them gives me a non zero value


timeval end_time;
timeval Dbg_timer;

The above time structures where initialized with gettimeofday() at some point.

Below is how I calculated the time difference:

long int elaspsed_time_s  = end_time.tv_sec - Dbg_timer.tv_sec;
printf("elaspsed_time_s =%d -> end_time_tv_sec=%d  Dbg_timer_tv_sec=%d \n", 
        elaspsed_time_s,       end_time.tv_sec,    Dbg_timer.tv_sec);

The Output:

elaspsed_time_s =3 -> end_time_tv_sec=1631446699  Dbg_timer_tv_sec=1631446699

How is the above possible? What is really going on?


Solution

  • %d is not a proper conversion to use for the long int value elaspsed_time_s. (By the way, the correct spelling is “elapsed”.) Use %ld for elaspsed_time_s.

    %d is also not a proper conversion to use for the time_t values in the tv_sec member. On POSIX systems, time_t is an integer type, but it is not necessarily an int, as far as I know. To print a time_t value, you might convert it to a long int and print it with %ld:

    printf("elaspsed_time_s =%ld -> end_time_tv_sec=%ld  Dbg_timer_tv_sec=%ld \n", 
            elaspsed_time_s,
            (long int) end_time.tv_sec,
            (long int) Dbg_timer.tv_sec);
    

    Alternatively, you could include <stdint.h> and <inttypes.h> and print it via uintmax_t:

    printf("elaspsed_time_s =%ld -> end_time_tv_sec=%" PRIuMAX "  Dbg_timer_tv_sec=%" PRIuMAX " \n", 
            elaspsed_time_s,
            (uintmax_t) end_time.tv_sec,
            (uintmax_t) Dbg_timer.tv_sec);