【问题标题】:Running code periodically without another thread在没有另一个线程的情况下定期运行代码
【发布时间】:2021-04-14 06:24:57
【问题描述】:

这是我的代码:

while(1)
{
   if (fmod(get_elapsed_time(), 3.0) == 0.0)
   {
       printf("Hello World\n");
   }
}

get_elapsed_time 函数返回一个double,它是自程序启动以来经过的时间,以秒为单位,小数点后为毫秒。

所以这段代码应该每 3 秒打印一次 hello world,但事实并非如此,我不知道为什么。

【问题讨论】:

  • 用浮点数比较相等总是有风险的,尤其是在尝试测量时间时。例如,如果您碰巧在时间 2.9999 和时间 3.0001 调用 get_elapsed_time(),则模数在任何时候都不会为 0。然后您必须再等待 3 秒才能再次尝试(但失败)。
  • @user3386109 但如果我将其转换为int,它会一直打印到下一秒
  • 对于业余程序,只需使用 Sleep() 或 sleep(),具体取决于操作系统。
  • 这能回答你的问题吗? How to run something every t seconds in C?

标签: c time


【解决方案1】:

浮点数不准确。跟踪您上次打印的时间,当当前时间 >= 3 秒时,是时候打印更多内容了。

类似

float last_print_time = get_elapsed_time();
for(;;) {
  float current_time = get_elapsed_time();
  if (current_time - last_print_time >= 3.0) {
    printf("Beep!\n");
    last_print_time = current_time;
  }
}

【讨论】:

  • 喜欢这个? :if (get_time_elapsed() - stored_time >= 3.0)stored_time 是循环开始的时间,如果此条件为真,我将 stored_time 设置为当前时间,我仍然没有打印任何内容
  • stored_time 需要在循环外初始化,然后仅在打印内容时更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多