在 c 中实现时间延迟 [英] implement time delay in c

查看:25
本文介绍了在 c 中实现时间延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何准确地搜索这个..所以我没有找到任何东西..:S

I don't know exactly how to word a search for this.. so I haven't had any luck finding anything.. :S

我需要在 C 中实现时间延迟.

I need to implement a time delay in C.

比如我想做一些事情,然后等一分钟,然后继续做事情.

for example I want to do some stuff, then wait say 1 minute, then continue on doing stuff.

有意义吗?谁能帮帮我?

Did that make sense? Can anyone help me out?

推荐答案

在标准 C (C99) 中,您可以使用 time() 来执行此操作,例如:

In standard C (C99), you can use time() to do this, something like:

#include <time.h>
:
void waitFor (unsigned int secs) {
    unsigned int retTime = time(0) + secs;   // Get finishing time.
    while (time(0) < retTime);               // Loop until it arrives.
}

顺便说一下,这里假设 time() 返回一个 1 秒的分辨率值.我不认为这是标准强制要求的,因此您可能需要进行调整.

By the way, this assumes time() returns a 1-second resolution value. I don't think that's mandated by the standard so you may have to adjust for it.

为了澄清起见,这是我所知道的使用 ISO C99 执行此操作的唯一方式(并且问题仅标记为C",这通常意味着便携式解决方案是当然,仍然可以提供特定于供应商的解决方案.

In order to clarify, this is the only way I'm aware of to do this with ISO C99 (and the question is tagged with nothing more than "C" which usually means portable solutions are desirable although, of course, vendor-specific solutions may still be given).

无论如何,如果您在一个提供更有效方式的平台上,使用它.正如一些评论所指出的,像这样的紧密循环可能存在特定问题,使用关于 CPU 使用率和电池寿命.

By all means, if you're on a platform that provides a more efficient way, use it. As several comments have indicated, there may be specific problems with a tight loop like this, with regard to CPU usage and battery life.

任何体面的时间片操作系统都能够降低持续使用其完整时间片但电池电量可能更成问题的任务的动态优先级.

Any decent time-slicing OS would be able to drop the dynamic priority of a task that continuously uses its full time slice but the battery power may be more problematic.

然而,C 指定没有关于托管环境中的操作系统详细信息,这个答案仅适用于 ISO C 和 ISO C(因此不使用 sleepselect、Win32 API 调用或类似的东西).

However C specifies nothing about the OS details in a hosted environment, and this answer is for ISO C and ISO C alone (so no use of sleep, select, Win32 API calls or anything like that).

并记住 POSIX sleep 可以被信号中断.如果您沿着这条路走下去,您需要执行以下操作:

And keep in mind that POSIX sleep can be interrupted by signals. If you are going to go down that path, you need to do something like:

int finishing = 0; // set finishing in signal handler 
                   // if you want to really stop.

void sleepWrapper (unsigned int secs) {
    unsigned int left = secs;
    while ((left > 0) && (!finishing)) // Don't continue if signal has
        left = sleep (left);           //   indicated exit needed.
}

这篇关于在 c 中实现时间延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆