[英]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.