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

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top