Search code examples
c++overflow

how to get a delta-time by seconds in int32 and nanosecond in uint32 for cpp


i got some timestamp where seconds in int32 and nanosecond in uint32, i wish to get a accuracy delta-time, like:

int32   last_seconds; // = some value
int32   this_seconds; // = some value
uint32  last_nanosec; // = some value, e.g. 178922366
uint32  this_nanosec; // = some value, e.g. 58887157


float delta_seconds = float(this_seconds - last_seconds);
float delta_nanosec = float(this_nanosec - last_nanosec);

float delta_time = delta_seconds + delta_nanosec/1e9;

but i found this_nanosec - last_nanosec easily overflow as they are uint32 and frequently this_nanosec < last_nanosec, as example delta_nanosec = 4.17493, but delta_nanosec = -0.120035209 is more reasonable . (however, results of seconds look fine)

how can i get a accuracy delta-time as expected in this case? thanks


Solution

  • You could use your input timestamps to initialize timespec struct/s, then plug them in diff_timespec

    #include <time.h>
    #include <cinttypes>
    #include <iostream>
    
    double diff_timespec(const struct timespec *time1, const struct timespec * time0) 
    {
        return (time1->tv_sec - time0->tv_sec) + (time1->tv_nsec - time0->tv_nsec) / 1000000000.0;
    }
    
    int main(int, char**)
    {
        int32_t   last_seconds = 3; // = some value
        uint32_t  last_nanosec = 178922366; // = some value, e.g. 178922366
    
        int32_t   this_seconds = 6; // = some value
        uint32_t  this_nanosec = 58887157; // = some value, e.g. 58887157
    
        struct timespec last{last_seconds, last_nanosec}, now{this_seconds, this_nanosec};
    
    
        double delta_time = diff_timespec(&now, &last);
        std::cout << delta_time << std::endl;
    }
    

    output: 2.87996