我的简单游戏的计时器非常关闭...C++
My Simple Game's Timer is Very Off... C++
所以这是之前帖子中的相同游戏(链接在这里)。那篇文章的标题是"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;
}
相关文章:
- OpenGL大的3D纹理(>2GB)非常慢
- 为什么需要复制构造函数,在哪些情况下它们非常有用
- 为什么std::互斥需要很长的、非常不规则的时间来共享
- G++ C++17 类模板参数推导在非常特殊的情况下不起作用
- 使用浮点数和双精度数的非常小数字的数学
- 在打开多个其他窗口时使用全屏窗口时帧速率非常低
- 我从int x[3]得到的一个非常奇怪的输出;
- 反向迭代器在C++中非常奇怪的行为
- 将非常大的 int 转换为双倍,在某些计算机上会损失精度
- 我的自定义使用 std::unordered_map 的性能非常慢
- ifstream 尝试读取 9 到 13 之间的无符号字符时非常奇怪的行为
- 一个非常简单的win32套接字代码,但工作错误
- 非常快速地阅读 CSV 文件
- max_element() 给出非常奇怪的错误消息
- 将 mmap 内存用于开销非常低的循环缓冲区
- 内存映射文件访问非常慢
- 超过CPU时间限制:当MPI_Sent一个非常大的int*时
- QtWebengine 5.7.1的性能非常慢
- 如何非常快速地将数字添加到 Vector 中的一系列元素中
- 我在运行函数 GetVolumeInformation() 时得到非常随机的结果