你好我創建一個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);
}
'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的,對於例)。 –
謝謝,我改變了我的答案,建議'clock_gettime'。 –
非常感謝!我將不得不使用'clock_gettime()' –