gpt4 book ai didi

c - 我使用 difftime 的 c 函数有时会返回 65535

转载 作者:太空宇宙 更新时间:2023-11-04 06:28:27 27 4
gpt4 key购买 nike

我有一个函数,它使用 difftime 来检测通信心跳停止后的时间(以秒为单位)。这个函数可以每 50 毫秒运行一次。该函数似乎可以工作,但偶尔会返回 65535。我可以将执行减少到每秒一次,因为 difftime 的返回仅以秒为单位。但是不知道能不能解决问题。问题是因为我没有正确地将 difftime 返回从 double 转换回 uint16_t 吗?

这个程序在 ubuntu 64 位机器上运行。

请帮忙。谢谢。

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

最佳答案

查询时间前,阅读time(7)手册页(并再次阅读)。

我建议使用clock_gettime(2)与例如CLOCK_MONOTONICCLOCK_REALTIME,最好使用 double 进行时间计算(因为 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;
}

您可能希望通过测试 clock_gettime 是否失败并在失败时给出 NAN 来使该函数更有趣!这留给读者作为练习。对于 CLOCK_REALTIME 等,您还可以测量进程开始时的某个时间与当前时间之间的差异(即计算一个 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);

另见 clock(3)

关于c - 我使用 difftime 的 c 函数有时会返回 65535,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23278423/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com