2011-04-29 181 views
1
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 

回答

4

你它過於複雜 - 簡單:

time_t start = time(); 
for (;;) { 
    // try something 
    if (time() > start + 5) { 
     printf("5s timeout!\n"); 
     break; 
    } 
} 

time_t一般應該只是一個intlong int根據您的平臺,因爲1月1日統計的秒數在1970年

旁註:

int timeout = timeout_ms/1000; 

一秒由1000毫秒。

編輯 - 另注: 你最有可能,以確保其他線程(S)和/或事件處理可能發生的,所以包括某種線程閒置(使用sleep()nanosleep()或其他)。

+0

你好馬里奧。這工作。謝謝。是的,這將是一個多線程應用程序。所以在我正在檢查時間的while循環中。我應該在那裏休息以暫停當前線程,以便其他線程可以發生。但是,如果這是多線程的話。無論如何,這些線程會發生,因爲它們會在另一個線程中?你是這個意思嗎?謝謝。 – ant2009 2011-04-29 19:52:15

+1

他們應該(真的取決於您的操作系統的調度程序),但即使它閒置,您的應用程序仍將保持100%,這可能會減慢您等待的其他線程。如果你不想冒任何緩慢的風險,只需等待0毫秒。這聽起來很愚蠢,但它會爲操作系統提供一個方便的地方,即使您根本不在等待(在紙上),它也可以任務切換和處理事件。 – Mario 2011-04-29 20:31:47

+0

你好馬里奧,我更新了一些更新後的結果。你會說哪一個是最適合你的睡眠?謝謝。 – ant2009 2011-05-01 06:13:10

1

沒有調用Sleep()函數,這是一個非常糟糕的設計:您的循環將使用100%的CPU。即使你正在使用線程,你的其他線程也沒有太多時間運行,因爲這個線程將使用很多CPU週期。 您應該設計這樣的事情:

while(true) { 
    Sleep(100); // lets say you want a precision of 100 ms 
    // Do the compare time stuff here 
} 

如果你需要時間的精確度,並且使用不同的線程/進程,使用互斥(semaphores爲1的遞增/遞減)或臨界區,以確保時間您的功能比較不會被您自己的另一個進程/線程中斷。 我相信你的紅帽是一個System V所以你可以同步使用IPC

+0

您好Dranfi,我確實將睡眠設置爲100.我還將此作爲我的更新結果顯示在我的問題中。謝謝。 – ant2009 2011-05-01 06:13:49

+0

我真的很驚訝你的結果: 設置睡眠(100) - > 13%的CPU。 對於僅循環迭代10次/秒的循環,這仍然是很多CPU週期。 我可以問你在哪個CPU(和OS)上執行這個代碼? – dranfi 2011-05-01 06:54:43

+0

Fedora 15 x64,Atom N550 2核心4線程,DDR3 2GB。謝謝。 – ant2009 2011-05-01 10:14:15