gpt4 book ai didi

c - 如何在没有 clock_t 或定时器的情况下在 C 中执行时间循环?

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

我想在几秒钟内的某个时间执行 2 个不同的输出,一个接一个。并使用 keyEvent 更改交换时间。这是想法。

[Every 10 seconds]
1 2 3 4 5 6 7 8 9 (10) 11 12 13 14 15 16 17 18 19 (20) (→ second-from timer lib.)
Display Output 1 = 1-10 second
Display Output 2 = 11-20 second, (then Output 1 again, etc)

[Every 5 seconds]
1 2 3 4 (5) 6 7 8 9 (10) 11 12 13 14 (15) 16 17 18 19 (20)(→ second-from timer lib.)
Display Output 1 = 1-5 second
Display Output 2 = 6-10 second
Display Output 1 = 11-15 second, (then Output 2 again, etc)

我一直在寻找问题,例如 Timed C Program LoopHow to use seconds (time) in C program as a counter?我只找到那些带有定时器和 clock_t 的。我不打算使用计时器和时钟,因为我已经使用 utilTimer 库来实时返回秒数。这是我的 keyEvent 代码:

if (key == '1' ) {
delay=10;
}
if (key == '2' ) {
delay=5;
}
if (key == '3' ) {
delay=3;
}
if (key == '4' ) {
delay=1;
}

如何实现时间循环?到目前为止,我正在使用 mod 进行循环,但是使用 mod 时,输出仅在值满足 mod 时执行一次。由于我是实时运行的,因此很难设置循环的最大值。所以我还是有点迷茫,还没有达到我的目标。

for (int count = 0; true; count++) {
if (count % delay == 0) {
//push output 1 every defined delay - in seconds
}
else {
//push another output
}
}

有什么建议吗?

[编辑]

我在 Mac 上运行一个简单的 C 程序。基本上我想做的是我想在这种情况下推送一个输出字符串输出和一个图像,所以几秒钟后字符串和图像将重复变化。我希望能够使用 key 控制变化的频率。

最佳答案

您需要跟踪上次更改图像和字符串的时间。然后用当前时间减去上次时间,如果差值大于延迟时间,则输出新图像和字符串,然后将上次时间变量更新为当前时间。

如果您为计时器使用无符号值,则不会遇到翻转问题(对于有符号整数会溢出,并导致未定义的行为)。

unsigned now;        // from your timer
unsigned last_event; // the last time you sent stuff out
unsigned delay; // the time between output events

while (1)
{
if ((now - last_event) >= delay)
{
// send out your string and image
last_event = now;
}
else
{
// keep waiting, and do whatever else you want
// update now as appropriate from timer
}
}

我在上面使用 while (1) 是为了传达这样的想法,即 while 循环中的代码被频繁执行。这不需要,而且在实践中可能不会是 while 循环。应该是

  • 嵌入式应用程序中的一段“ super 循环”
  • 在 RTOS 任务中
  • 在一个大的操作系统线程中
  • 在游戏程序的“框架”调用中

关于c - 如何在没有 clock_t 或定时器的情况下在 C 中执行时间循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52798387/

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