My c-function using difftime returns 65535 sometimes

I have a function that uses diffftime to determine the time in seconds, as the interruption is interrupted. This feature can work as fast as every 50 milliseconds. The function seems to work, except that it returns 65535. I can shorten the execution to one second, since the difftime returns only after a second. But I do not know if this will fix the problem. Is this a problem because I am incorrectly returning back to uint16_t from double?

This program runs on a 64-bit ubuntu machine.

Please, help. Thank you

uint16_t commlost(uint16_t heartbeat_read_cur)
{  
    time_t current_time;  
    static time_t previous_time;  
    static uint16_t commlost_secs_cur = 0;  
    static uint16_t commlost_secs_prev = 0;  
    static uint16_t heartbeat_read_prev = 0;  
    static bool first_time = TRUE;
    if (first_time)
    {
        previous_time = time(NULL);
        first_time = FALSE;
    }

    time(&current_time);

    commlost_secs_prev = commlost_secs_cur;

    if(heartbeat_read_prev == heartbeat_read_cur)
    {

        commlost_secs_cur += difftime(current_time, previous_time);
    }
    else
    {
        heartbeat_read_prev = heartbeat_read_cur;
        commlost_secs_cur = 0;
    }

    previous_time = current_time;

    return (commlost_secs_cur);
}
0
source share
2 answers

difftime() , time_t , . , - , . , POSIX time_t , difftime() , :

commlost_secs_cur += current_time - previous_time ;

, , , , :

int commlost(uint16_t heartbeat_read_cur)
{  
    time_t current_time = time(0) ;  
    static time_t heartbeat_timestamp = 0 ; 
    static uint16_t heartbeat_read_prev  ;

    // If first time, or heartbeat changed...
    if( heartbeat_timestamp == 0 || heartbeat_read_prev != heartbeat_read_cur)
    {
        // ... timestamp heartbeat
        heartbeat_timestamp = time(0) ;

        // ... keep last heartbeat
        heartbeat_read_prev = heartbeat_read_cur ;
    }

    // Return seconds since last heartbeat timestamp
    return current_time - heartbeat_timestamp ;
}

, uint16_t ; , .

+1

, (7) man- ( ).

clock_gettime (2), . CLOCK_MONOTONIC CLOCK_REALTIME double ( a struct timespec ).

uint16_t .

inline double double_gettime (clockid_t cid) {
  struct timespec ts = {0,0};
  clock_gettime(cid, &ts);
  return (double)ts.tv_sec + 1.0e-9*ts.tv_nsec;
}

, fancier, , clock_gettime NAN, ! . , CLOCK_REALTIME .., (.. a struct timespec double)

,

double tstart = double_gettime(CLOCK_REALTIME);
some_long_computation();
double tend = double_gettime(CLOCK_REALTIME);
printf ("needed %f seconds to compute\n", tend-tstart);

. (3)

+3

All Articles