我们知道,一个窗口如果是我们自己创建的,我们可以在 WndPro 里处理按键消息,但对于使用第三方库(或控制台)我们不便于找到那个窗口的 WndProc,于是我想用用枚举毫秒的方法,下面的程式模拟了一个类似打“怪兽”的过程:
#include <iostream>
#include <Windows.h>
#include <conio.h>
using namespace std;
int os;
int main() {
int last;
for (unsigned timer = 1; ; timer++) {
if (kbhit()) {
char op = getch();
if (op == ' ') {
if (timer > last) {
os++;
last = timer + 100;
cout << "Bit! \n";
}
}
else break;
}
if (timer % 100 == 0) cout << "Hit! \n";
Sleep(1);
}
cout << os;
return 0;
}
在这里我们可以看到,理论上每 100ms 会自动 Hit,当你按下空格键时会 Bit, 并且在此后的 100ms 里你再次按下空格键并不会输出。
但是事实上,每一个 Hit 输出的时间间隔远远大于 100 ms,甚至能在 1 秒左右。
1s 内能执行 108 条语句,那平均每毫秒也能执行 105 条,我 O(1) 的时间是远远低于 1ms 的,那么请问为什么会造成这么大的时间间隔呢?