Jul 25 2009

Creating a High Performance Message Loop

I've heard criticisms of the Windows and Windows Mobile environment because of the way that the default message pump is implemented and the performance cap that it puts on applications that require constant refreshing of the UI (such as games).  The problem is that the default message pump is geared towards business applications and minimizing CPU usage.  If you need to make a high performance application or game then you should use a different message pump implementation. You should not be waiting on WM_PAINT message.  You should just go ahead and repaint the screen.   Given that many developers will never alter the default message pump implementation it is preferable to have one that has low CPU usage by default.  If you want to do performance graphics you need a loop similar to the following:

	
bool keepRunning = true;
while(keepRunning)
{
	if(PeekMessage(&msg,NULL,0,0,TRUE))
	{
		if(msg.message==WM_QUIT)
			keepRunning=false;
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) 
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}
	else
	{
		//Execute Game Logic Here and rendering here
	}
}

The default message pump handling would be blocked when there are no messages to process and the WM_PAINT message (being low priority) would always be the last thing on the queue. In the message pump above the application will be able to concentrate on the game logic and give attention to messages on the queue when they arrive.  We'll talk about  other things that you would need to do for a game in coming posts.

Tags: