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

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

本文关键字:C++ 非常 计时器 简单 游戏 我的      更新时间:2023-10-16

所以这是之前帖子中的相同游戏(链接在这里)。那篇文章的标题是"C++时钟不工作",我已经固定了时钟,"万岁!现在,我用来计算持续时间的过程似乎被破坏了。我总是得到"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() 实际返回的是程序在 CPU 内核上主动执行的总时间的统计。 也就是说,程序"休眠"的任何时间(例如,当它等待输入时)不会导致 clock() 返回的值增加。 正如手册页所说:

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