Reputation: 8732
i've found this piece of code and tested it.
#include <time.h>
int main ()
{
time_t start_time;
time_t current_time;
int TIMEOUT=5;
start_time = time(NULL);
current_time = time(NULL);
while (current_time < start_time + TIMEOUT)
{
//do everything here
current_time = time(NULL);
}
}
It works like a charm, but it takes completely one cpu off. Is there a way to don't waste so much cpu? Thanks
Edit, I can't use sleep, i must do other thing during waiting
Upvotes: 0
Views: 605
Reputation: 27552
You need to use a timer. There are several APIs to do this.
Just using alarm
is the simpliest.
There is setitimer/getitimer
.
There is the timer_create/timer_destroy/timer_settime
family.
Each has their own strengths offset by their own complexities.
Upvotes: 2