run an infinite loop for a while in c
I want to run an infinite loop for a while. Basically, i want to have something like this
//do something
w开发者_StackOverflowhile(1){
//do some work
}
//do some other thing
but i want the running time of the loop to be fixed, example, the loop could be running for 5 seconds. Do somebody have an idea?
Just do sleep(5)
(include unistd.h
). You can use it like this:
// do some work here
someFunction();
// have a rest
sleep(5);
// do some more work
anotherFunction();
If you're doing work inside the loop, you can do (include 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.
}
Try using clock().
#include <time.h>
clock_t start = clock();
while (1)
{
clock_t now = clock();
if ((now - start)/CLOCKS_PER_SEC > 5)
break;
// Do something
}
First of all, consider using the sleep
function if possible. If you have to do actual work for a specified time period, which I find unlikely, the following ugly solution would work:
#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 */
}
/* ... */
}
A solution using time.h
would also be possible, and perhaps simpler and/or more accurate, depending on context:
#include <time.h>
int main(void){
/* ... */
clock_t start = clock();
while(clock() - start < 5 * CLOCKS_PER_SEC) {
/* Do work */
}
/* ... */
}
Pseudo-code:
starttime = ...;
while(currentTime - startTime < 5){
}
If you don't want to call a time getting function each time through the loop and are on a system that has alarm
(POSIXes like Unix, Linux, BSD...) you can do:
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.
...
Signals can have other side effects (like kicking you out of system calls). You should look into these before relying on them.
Not tested; resolution is very coarse.
#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;
}
If /* work */ takes more than 5 seconds, the loop will take more than 5 seconds.
If /* work */ takes 1.2 seconds, the loop will execute approximately 5 times for a total of 6 seconds
精彩评论