gcc (gcc) 4.6.0 20110419 (red hat 4.6.0-5)
i trying time of start , end time. , difference between them.
the function have creating api our existing hardware.
the api wait_events take 1 argument time in milli-seconds. trying start before while loop. , using time number of seconds. after 1 iteration of loop time difference , compare difference time out.
many suggestions,
/* wait event specified time out. * if event occurs before time out return 0 * if event timeouts out before event return -1 */ int wait_events(int timeout_ms) { time_t start = 0; time_t end = 0; double time_diff = 0; /* convert seconds */ int timeout = timeout_ms / 100; /* initial time */ start = time(null); while(true) { if(open_device_flag == true) { device_evt.event_id = event_dev_open; return true; } /* end time after each iteration */ end = time(null); /* difference between times */ time_diff = difftime(start, end); if(time_diff > timeout) { /* timed out before getting event */ return false; } } }
the function call this.
int main(void) { #define timeout 500 /* 1/2 sec */ while(true) { if(wait_events(timeout) != 0) { /* process incoming event */ printf("event fired\n"); } else { printf("event timed out\n"); } } return 0; }
=============== edit updated results ==================
1) no sleep -> 99.7% - 100% cpu 2) setting usleep(10) -> 25% cpu 3) setting usleep(100) -> 13% cpu 3) setting usleep(1000) -> 2.6% cpu 4) setting usleep(10000) -> 0.3 - 0.7% cpu
you're overcomplicating - simplified:
time_t start = time(); (;;) { // try if (time() > start + 5) { printf("5s timeout!\n"); break; } }
time_t
should in general int
or long int
depending on platform counting number of seconds since january 1st 1970.
side note:
int timeout = timeout_ms / 1000;
one second consists of 1000 milliseconds.
edit - note: you'll have ensure other thread(s) and/or event handling can happen, include kind of thread inactivity (using sleep()
, nanosleep()
or whatever).
Comments
Post a Comment