繁体   English   中英

在c中运行无限循环一段时间

[英]run an infinite loop for a while in c

我想运行无限循环一段时间。 基本上,我想要这样的东西

//do something

while(1){
  //do some work
}

//do some other thing

但是我希望循环的运行时间是固定的,例如,循环可以运行5秒钟。 有人有主意吗?

只需执行sleep(5) (包括unistd.h )即可。 您可以像这样使用它:

// do some work here
someFunction();    

// have a rest
sleep(5);

// do some more work
anotherFunction();

如果您正在循环中进行工作,则可以执行以下操作(包括time.h ):

// set the end time to the current time plus 5 seconds
time_t endTime = time(NULL) + 5;

while (time(NULL) < endTime)
{
    // do work here.
}

尝试使用clock()。

#include <time.h>

clock_t start = clock();

while (1)
{
    clock_t now = clock();
    if ((now - start)/CLOCKS_PER_SEC > 5)
        break;

    // Do something
}

首先,请考虑尽可能使用sleep功能。 如果您必须在指定的时间段内进行实际工作(我认为这不太可能),则以下丑陋的解决方案将起作用:

#include <signal.h>
int alarmed = 0;
void sigh(int signum) {
    alarmed = 1;
}
int main(void){
    /* ... */
    signal(SIGALRM, &sigh);
    alarm(5); // Alarm in 5 seconds
    while(!alarmed) {
        /* Do work */
    }
    /* ... */
}

根据上下文,使用time.h的解决方案也是可能的,并且可能更简单和/或更准确:

#include <time.h>
int main(void){
    /* ... */
    clock_t start = clock();
    while(clock() - start < 5 * CLOCKS_PER_SEC) {
        /* Do work */
    }
    /* ... */
}

伪代码:

starttime = ...;

while(currentTime - startTime < 5){

}

未经测试; 分辨率非常粗糙。

#include <time.h>
#define RUNTIME 5.0 /* seconds */

double runtime = 0;
double start = clock(); /* automatically convert clock_t to double */
while (runtime < RUNTIME / CLOCKS_PER_SEC) {
    /* work */
    runtime = clock() - start;
}

如果/ *工作* /花费了5秒钟以上,则循环将花费5秒钟以上。

如果/ *工作* /需要1.2秒,则循环将执行 5次,总共6秒

如果您不想每次通过循环都调用时间获取功能,并且不想在有alarm的系统(Unix,Linux,BSD等POSIX)上运行,可以执行以下操作:

静态volatile int超时= 0;

void handle_alrm(int sig) {
     timeout = 1;
}

int main(void) {
    signal(SIGALRM, handle_alrm);
    ...
    timeout = 0;
    alarm(5);
    while (!timeout) {
       do_work();
    }
    alarm(0); // If the signal didn't fire yet we can turn it off now.
    ...

信号可能会产生其他副作用(例如将您踢出系统调用)。 在依赖它们之前,您应该研究这些。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM