我的简单游戏的计时器非常不... C++

My Simple Game's Timer is Very Off... C++

所以这是之前 post 的同一款游戏(Link 是 )。那个 post 的标题是 "C++ Clock Not Working" 我已经修好了时钟,"Hooray!"。现在我用来计算持续时间的过程似乎被打破了。我总是得到 'x.y'e-05,其中时间应该以秒为单位,但计时器在 'x.y'e-05 之前停止。 05 是否也意味着它在基数 8 中?如果是为什么???

我确定我缺少一个非常简单的解决方案。任何答案将不胜感激...

代码:

          do {
                //Procedere For Each Round

                clock_t start;

                //Clock
                start = clock();

                cout<<"The number is:  "<< actualNumber<<endl;
                getline(cin, numberGuessed);
                intNumberGuessed = stoi(numberGuessed);

                clock_t finish;
                finish = clock();

                double elapsed = (double)(finish-start);


                duration = elapsed/CLOCKS_PER_SEC;

                cout<<"The Duration Is:  "<< duration<<endl; //FOR TESTING...

                //Test User's input

               //timeForInput is chosen earlier and is either 1,2,or 5.
                if((intNumberGuessed == actualNumber) && (duration <= (timeForInput/100000))){
                    score += 1;
                    gameOver = 0;

                } else if ((intNumberGuessed != actualNumber) || (duration >= (timeForInput/100000))) {
                    gameOver = 1;
                }

                //Reset Number
               actualNumber = rand() % 4 + 1;

               //Reset Clock


            } while (gameOver != 1);
        }

        cout<<"You Failed!"<<endl;
        sleep(1);
        cout<<"Your Score Was:  "<<score<<endl;

        return 0;

问题是 clock() 并没有像您想象的那样工作。你的印象是 clock() returns 代表挂钟时间的值(并非不合理,考虑到函数名称),但 clock() 实际上返回的是总时间的统计 当您的程序一直在 CPU 核心 上积极执行时。也就是说,您的程序花费 "asleep" 的任何时间(例如,当它等待输入时)都不会导致 clock() 返回的值增加。正如 man page 所说:

The clock() function returns an approximation of processor time used by the program.

这就解释了为什么您测量的数字非常小(x.ye-05 是科学记数法,即 x.y * 10^-5 秒)——您的程序执行时间很少,因为在您测量的大部分时间间隔内,您的程序处于休眠状态,阻塞在 getline() 中等待用户输入内容。

所以 clock() 不会为您的目的工作。你最好打电话给例如gettimeofday() 并将其结果转换为以微秒为单位的值,如下所示:

// Returns a "current wall clock time" value, in microseconds
unsigned long long GetWallClockTimeInMicroseconds()
{
   struct timeval tv;
   gettimeofday(&tv, NULL);
   return ((unsigned long long)tv.sec)*1000000 + tv.tv_usec;
}