程序中的定时器太慢

Timer in program is too slow

你好,我正在创建一个 speedcube 计时器,我只是让时间居中,但后来我注意到它的时间太慢了,我尝试将 usleep 功能从 1000 更改,但它不是快就是慢,任何想法?

#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);
}

您永远不应依赖内部累加器来累加已用时间。这样做不仅捕获了 usleep() 消耗的时间,还捕获了格式化该字符串和任何其他计算的执行时间(字符串格式可能是大的)。

相反,在开始时获取系统时间。然后,每当您需要采样新的时间量时,再次获取系统时间并从现在时间减去开始时间。这会给你经过的时间,然后你可以从那里调整。

您的代码似乎是在假设您的进程可以每毫秒 运行 可靠地执行一次的前提下编写的,但您可能 运行 将其运行在必须执行其他任务的操作系统上,因此您不会每毫秒到达 运行。此外,usleep 可能不像您希望的那样准确,并且您没有考虑进行计算和将数据输出到终端所需的时间。

可以使用 usleep 来节省 CPU 时间。但是当你想知道现在是几点以便向用户显示时间时,你应该使用一个实际获取时间的函数,比如 C clock_gettime 函数。