Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Game Loop 50% CPU on Dual Core

The game loop alone is using 50% of CPU Usage, I haven't done any rendering work yet. What I'm doing here?

        while(true)
        {
            if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
            {
                    if(msg.message == WM_QUIT || 
                           msg.message == WM_CLOSE || 
                           msg.message == WM_DESTROY)
                            break;

                    TranslateMessage(&msg);
                    DispatchMessage(&msg);                   
            }
            else
            {
                    //Run game code, break out of loop when the game is over

            }
        }
like image 234
cpx Avatar asked Nov 29 '22 06:11

cpx


2 Answers

Classic busy/wait loop. Your CPU is busily checking (and rechecking ad infinitum) for messages. You need to wait for messages in a blocking way or, more likely, use a timer that periodically wakes up your game thread so it can do its work. The game thread would then go away until the next time it is woken up.

like image 159
tvanfosson Avatar answered Dec 10 '22 17:12

tvanfosson


You have created a busy-wait loop. You are probably using 100% of one core, thus 50% of a dual core.

You need to find a way to block on read (in a separate thread), block and fall out of an I/O call as necessary, or do something else useful in the thread. Each strategy has its advantages and disadvantages. Separate threads need synchronized communication methods such as mutexs. Falling out of I/O means nothing else useful happens in this thread when there are no messages. Doing something else in the loop can result in lumpy processing (the "something else" gets processed more on less messages. less on more messages).

like image 41
kmarsh Avatar answered Dec 10 '22 17:12

kmarsh