2017-05-10 8 views
0

안녕하세요 저는 스피드 큐브 타이머를 만들었습니다. 저는 시간 중심을 가졌지 만 그 시간이 너무 느리다는 것을 알았습니다. 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 시간을 절약하기 위해 usleep을 사용해도됩니다. 그러나 사용자에게 시간을 표시하는 데 걸리는 시간을 파악하려면 C clock_gettime 기능과 같이 실제로 시간을 가져 오는 기능을 사용해야합니다.

+2

'time()'함수는 1 초의 세밀도를 제공합니다. 밀리 초 타이밍의 경우 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 Sierra에서는 사용할 수 있지만 이전 버전의 Mac OS X에서는 사용할 수 없습니다. 예). –

+0

고마워, 나는 'clock_gettime' 제안에 대한 나의 대답을 변경했습니다. –

+0

감사합니다. 나는'clock_gettime()'을 사용해야 할 것이다. –

1

경과 된 벽 시간을 누적하기 위해 내부 누적기를 절대 사용해서는 안됩니다. 이렇게하면 usleep()에 의해 소비되는 시간뿐만 아니라 해당 문자열 및 다른 계산 형식의 실행 시간 (문자열 형식이 큰 형식 일 가능성이 높음)을 캡처합니다.

대신 시작시 시스템 시간을 가져옵니다. 그런 다음 새 시간을 샘플링해야 할 때마다 시스템 시간을 다시 가져 와서 지금부터 시작 시간을 뺍니다. 시간이 경과하면 조정할 수 있습니다.