Reputation: 523
It is my first time working with Windows applications and I am a bit frustrated. I just have a simple code that creates a Win32(Visual C++) GUI application, but as soon as I start the executable my CPU goes up to 30%(Over the application), in my search to solve this I have found someone saying that sleep for 10ms in the message loop(GetMessage or PeekMessage) would solve this and it indeed did. But as I don't really enjoy sleeping my code all of a sudden and by the fact that this is a event handler loop I would love an explanation on how to solve this.
A peek on the "troublesome area".
while (TRUE) {
if (PeekMessage(&g_Msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&g_Msg); // translate keystroke messages into the right format
DispatchMessage(&g_Msg); //Send the message to the WindowProc function
if (g_Msg.message == WM_QUIT)
break;
} else {
// Run d3d code here
}
// Sleep(1); REDUCES CPU!
}
Thanks in advance
Caio Guedes
Upvotes: 6
Views: 3495
Reputation: 104559
A standard Windows application loop uses GetMessage. GetMessage blocks until there's input or something in the application that needs to run.
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
What you have coded is suitable and standard for a game - when you want DirectX to render frames as fast as possible while still pumping messages for other in-process windows and Win32 APIs. What you have coded is essentially using an entire core of CPU when you code it this way. (If you have a quad-core CPU, you're using at least 25%, so that 30% measurement seems accurate).
The periodic Sleep(0)
or Sleep(1)
statement is useful to allow your main thread to yield to other threads and processes. You'll sacrifice a little frame rate, but sometimes that's necessary if the game has other threads for networking and sound. But since you have a multi-core CPU, then you might not need to do that since the other cores can service those threads.
In the old days, before hyperthreading and multi-core, doing the Sleep
statement was the normal way to not be a total resource hog. It allowed other background applications on Windows to be able to run.
Upvotes: 5
Reputation: 21
You should use GetMessage(), it's a blocking function. It will block until there is something to process.
Upvotes: -1