Setup: I have this program in c++:
#include <windows.h>
using namespace std;
int main(){
HWND window;
AllocConsole();
window = FindWindowA("ConsoleWindowClass", NULL);
ShowWindow(window,0);
while (1){
if (GetKeyState('A'))
{
system("start love.mp3");
return 0;
}
}
return 0;
}
So the program runs as a process and waits until the key A is pressed. And then it plays the love.mp3 file 🙂
However, when the program is waiting it uses up 25% of the CPU usage.
Qustion: Is there a way to reduce this so that the program doesn’t consume so much of the CPU?
Calling
Sleepin the loop is sort of effective, but IMO, it’s clearly the wrong way to go.Instead, I’d do a blocking read, then check if the result was
A, and do your thing when it is:This won’t miss keystrokes, and it’ll use even less CPU time than a loop that calls
Sleep.