gcc (GCC) 4.6.0 20110419 (Red Hat 4.6.0-5)
我想獲取開始和結束時間的時間。並獲得它們之間的差異。使用時間和difftime創建超時
我有的功能是爲我們現有的硬件創建一個API。
API wait_events帶有一個以毫秒爲單位的時間參數。所以我想在while循環之前開始。並用時間來獲得秒數。然後,循環的1次迭代獲得時間差,然後將該差異與超時進行比較。
非常感謝您的任何建議,
/* Wait for an event up to a specified time out.
* If an event occurs before the time out return 0
* If an event timeouts out before an event return -1 */
int wait_events(int timeout_ms)
{
time_t start = 0;
time_t end = 0;
double time_diff = 0;
/* convert to seconds */
int timeout = timeout_ms/100;
/* Get the initial time */
start = time(NULL);
while(TRUE) {
if(open_device_flag == TRUE) {
device_evt.event_id = EVENT_DEV_OPEN;
return TRUE;
}
/* Get the end time after each iteration */
end = time(NULL);
/* Get the difference between times */
time_diff = difftime(start, end);
if(time_diff > timeout) {
/* timed out before getting an event */
return FALSE;
}
}
}
,將調用會是這樣的功能。
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;
}
===============編輯與更新的結果==================
1) With 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
你好馬里奧。這工作。謝謝。是的,這將是一個多線程應用程序。所以在我正在檢查時間的while循環中。我應該在那裏休息以暫停當前線程,以便其他線程可以發生。但是,如果這是多線程的話。無論如何,這些線程會發生,因爲它們會在另一個線程中?你是這個意思嗎?謝謝。 – ant2009 2011-04-29 19:52:15
他們應該(真的取決於您的操作系統的調度程序),但即使它閒置,您的應用程序仍將保持100%,這可能會減慢您等待的其他線程。如果你不想冒任何緩慢的風險,只需等待0毫秒。這聽起來很愚蠢,但它會爲操作系統提供一個方便的地方,即使您根本不在等待(在紙上),它也可以任務切換和處理事件。 – Mario 2011-04-29 20:31:47
你好馬里奧,我更新了一些更新後的結果。你會說哪一個是最適合你的睡眠?謝謝。 – ant2009 2011-05-01 06:13:10