# 我使用 difftime 的 c 函数有时会返回 65535(My c-function using difftime returns 65535 sometimes)

``````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 bool first_time = TRUE;
if (first_time)
{
previous_time = time(NULL);
first_time = FALSE;
}

time(&current_time);

commlost_secs_prev = commlost_secs_cur;

{

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

previous_time = current_time;

return (commlost_secs_cur);
}
``````

`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 ;

// If first time, or heartbeat changed...
{
// ... timestamp heartbeat
heartbeat_timestamp = time(0) ;

// ... keep last heartbeat
}

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

``````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;
}
``````

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