我想暂时运行无限循环。基本上,我希望有这样的东西
//do something
while(1){
//do some work
}
//do some other thing
但我希望修复循环的运行时间,例如,循环可以运行5秒。 有人有想法吗?
答案 0 :(得分:9)
只需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.
}
答案 1 :(得分:9)
尝试使用clock()。
#include <time.h>
clock_t start = clock();
while (1)
{
clock_t now = clock();
if ((now - start)/CLOCKS_PER_SEC > 5)
break;
// Do something
}
答案 2 :(得分:1)
首先,如果可能,请考虑使用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 */
}
/* ... */
}
答案 3 :(得分:0)
的伪代码:
starttime = ...;
while(currentTime - startTime < 5){
}
答案 4 :(得分:0)
未经测试;分辨率非常粗糙。
#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;
}
如果/ * work * /花费的时间超过5秒,则循环时间将超过5秒。
如果/ * work * /需要1.2秒,循环将执行大约 5次,共计6秒
答案 5 :(得分:0)
如果你不希望每次通过循环调用时间获取函数并且在具有alarm
的系统(如Unix,Linux,BSD等POSIX)上,你可以这样做:
static volatile int timeout = 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.
...
信号可能有其他副作用(比如踢你的系统调用)。你应该在依赖它们之前研究这些。