2017-05-10 59 views
0

你好我創建一個speedcube計時器我剛拿到的時候中心,但後來我發現,它的時間太慢了,我試着從1000改變usleep功能,但它是要麼快速或減慢任何想法?定時器程序太慢

#include <ncurses.h> 
#include <stdlib.h> 
#include <unistd.h> 


int main() 
{ 
    int minutes = 0, milliseconds = 0, seconds = 0, x = 0, y = 0, text = 6, textminutes = 0, textseconds = 0, textmilliseconds = 0; 

    initscr(); 
    while(1) 
    { 
     /*This block of code centers the text on the screen by incrementing each variable by one 
    for each number starting at ten, Then prints the time.*/ 
     getmaxyx(stdscr,y,x); 
     if (seconds == 60 && minutes == 10){ 
    textminutes += 1; 
     } 
     if (milliseconds == 1000 && seconds == 10){ 
    textseconds += 0; 
     } 
     if (milliseconds == 10){ 
    textmilliseconds += 1; 
     } 
     else if (milliseconds == 100) 
    { 
    textmilliseconds += 1; 
    } 
     else if(milliseconds == 1000) 
     { 
     textmilliseconds += 1; 
     } 
     int left_row = (x/2) - (3 + textminutes + textseconds + textmilliseconds/2); 
     mvprintw(y/2, left_row,"%d : %d : %d", minutes, seconds, milliseconds); 

     /*Sleep for 1 millisecond the increment the milliseconds 
    var i don't think that the timing is right though. 
    Then it refreshes and clears the screen to fetch the new contents.*/ 
     usleep(1000); 
     milliseconds++; 
     if(milliseconds == 1000) 
     { 
     milliseconds = 0; 
    textmilliseconds -= 2; 
     seconds++; 
    if(seconds == 60) 
     { 
     seconds = 0; 
     textseconds -= 1; 
     minutes++; 
     } 
     }  
     refresh(); 
     clear(); 
     } 
    endwin(); 
    return(0); 
} 

回答

2

您的代碼似乎與你的程序能夠可靠地運行一次,每毫秒的假設來編寫的,但你可能運行它的操作系統具有執行其他任務上,這樣你就不會得到運行每毫秒。此外,睡眠可能不如您所希望的那樣準確,並且您沒有考慮將您的計算和數據輸出到終端所需的時間。

這是確定使用usleep以節省CPU時間。但是當你想知道什麼時候向用戶顯示時間時,你應該使用一個實際上可以獲得時間的函數,比如C clock_gettime函數。

+2

'time()'函數給出了一秒的粒度。對於毫秒定時,對POSIX系統上,使用['clock_gettime()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_gettime.html)或也許 ['函數gettimeofday()'](HTTP: //pubs.opengroup.org/onlinepubs/9699919799/functions/gettimeofday.html) - 後者已經過時,但更廣泛地提供('clock_gettime()'可以在MacOS上拉,但不是較早版本的Mac OS X的,對於例)。 –

+0

謝謝,我改變了我的答案,建議'clock_gettime'。 –

+0

非常感謝!我將不得不使用'clock_gettime()' –

1

您不應該依賴內部累加器來累計經過的掛壁時間。這樣做不僅可以捕獲usleep()消耗的時間,還可以捕獲該字符串和其他任何計算(字符串格式可能是最大的格式)的執行時間。

相反,獲得在啓動系統時。然後,無論何時您需要抽取新的時間量,再次獲取系統時間並從現在時間中減去開始時間。這會給你經過的時間,然後你可以從那裏調整。