实现在C延时 [英] implement time delay in c

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

问题描述

我不知道究竟如何词来形容一个搜索..所以我没有任何运气找到任何东西..:•

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.

例如我想要做一些东西,然后等待说1分钟,然后继续做的东西。

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),你可以使用时间()来做到这一点,是这样的:

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.
}

顺便说一句,这是假定时间()返回一个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.

任何像样的时间切片OS将能够放弃,不断地利用其全部时间片,但电池电量可能会更加困难任务的动态优先级。

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.

不过ç指定的没有的有关在托管环境中操作系统的详细信息,而这个答案是ISO C和ISO C单独(所以没有使用睡觉选择,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 睡眠 可以通过信号中断。如果你的的打算走这条路,你需要做的是这样的:

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天全站免登陆