2013-10-12 52 views
0

如何調用方法/函數每秒50次,然後計算所花費的時間,如果花費的時間少於一秒,那麼睡眠時間爲(1-timespent)秒。如何在一秒鐘內調用方法/函數50秒

下面是僞代碼

while(1) 
{ 
    start_time = //find current time 
    int msg_count=0; 
    send_msg(); 
    msg_count++; 

    // Check time after sending 50 messages 
    if(msg_count%50 == 0) 
    { 
    curr_time = //Find current time 
    int timeSpent = curr_time - start_time ; 
    int waitingTime; 

    start_time = curr_time ; 

    waitingTime = if(start_time < 1 sec) ? (1 sec - timeSpent) : 0; 
    wait for waitingTime; 
    } 
} 

我是新與定時器的API。任何人都可以幫助我瞭解什麼是計時器API,我必須用它來實現這一點。我想要便攜式代碼。

+0

你想成爲多麼精確?你確定你的處理('send_msg'明顯,可能會被阻塞)總是少於20毫秒,即50Hz的週期? –

+1

[C++ Timer函數提供納秒級時間]的可能重複(http://stackoverflow.com/questions/275004/c-timer-function-to-provide-time-in-nano-seconds) – Joe

回答

2

首先,閱讀time(7)手冊頁。

然後您可能需要撥打timer_create(2)來設置計時器。要查詢關於時間的信息,請使用clock_gettime(2)

您可能想要等待並複用某些輸入和輸出。 poll(2)對此很有用。睡的少量時間不使用CPU考慮nanosleep(2)

如果使用定時器做信號,讀取​​因爲信號處理程序僅限於異步信號安全功能要小心(考慮具有信號處理器,其只是設置了一些全球性的volatile sig_atomic_t標誌)。您也可能對Linux特定timerfd_create(2)感興趣(您可以將poll或傳遞給您的事件循環)。

您可能需要使用一些現有的event loop庫,如libeventlibev(或來自GTK /油腔滑調,Qt的,等等),這往往是使用poll(或票友的東西)。 linux特定的eventfd(2)signalfd(2)可能會非常有幫助。

Advanced Linux Programming也是有用的閱讀。

如果send_msg是做網絡I/O,你可能需要重新設計周圍的一些事件循環程序(可能是你自己的,基於poll) - 你需要複用(即poll)兩種網絡發送和網絡臨危。 continuation-passing style然後是一個有用的範例。