我想运行一段时间的无限循环。基本上,我想要这样的东西
//do something
while(1){
//do some work
}
//do some other thing
但我希望循环的运行时间是固定的,例如,循环可以运行 5 秒。有人有想法吗?
我想运行一段时间的无限循环。基本上,我想要这样的东西
//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.
}
尝试使用时钟()。
#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 */
}
/* ... */
}
如果您不想每次通过循环调用时间获取函数并且在具有alarm
(POSIXes,如 Unix、Linux、BSD ...)的系统上,您可以执行以下操作:
静态易失性 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.
...
信号可能有其他副作用(例如将您踢出系统调用)。在依赖它们之前,您应该研究这些。
未测试;分辨率非常粗糙。
#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 秒
伪代码:
starttime = ...;
while(currentTime - startTime < 5){
}