help: 100% CPU usage..

This topic is 4246 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Whenever I launch my (opengl) game.. the cpu usage goes up to 100%. Is this normal? my game doesnt even do anything.. it just draws a tile map on the screen and that's it. Here is the code that's causing high cpu usage.
bool DR::DrawScene()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glTranslatef(-11.0f, 9.0f,-35.0f);

char tile(' ');
int xpos(0);
int ypos(0);
int counter(0);

do
{
tile = map.CurrentMap()[counter];

if ( xpos > 21 ) { //goes to next line
xpos=0;
ypos++;
}

switch(tile)
{
case '0':
glColor3f(0.6f,0.3f,0.1f); //wall=dark brown
break;
case '1':
glColor3f(0.8f,0.3f,0.1f); //path=light brown
break;
case '2':
glColor3f(0.0f,0.0f,1.0f); //player=blue
break;
case '3':
glColor3f(1.0f,1.0f,0.0f); //gold=yellow
break;
case '4':
glColor3f(0.8f,0.3f,0.8f); //treasure box=orange
break;
case '5':
glColor3f(1.0f,0.6f,0.6f); //heart= pink
break;
case '6':
glColor3f(1.0f,0.0f,0.0f); //mine=red
break;
case '7':
glColor3f(0.0f,1.0f,0.0f); //store=teal
break;
case 'X':
glColor3f(0.0f,0.0f,0.0f); //game border
}

glVertex3f(float(xpos), float(-ypos), 0.0f);
glVertex3f(float(xpos), float(-ypos-1), 0.0f);
glVertex3f(float(xpos+1), float(-ypos-1), 0.0f);
glVertex3f(float(xpos+1), float(-ypos), 0.0f);
glEnd();

xpos++;
counter++;

} while(counter < map.CurrentMap().size());

return true;
}


map.CurrentMap() returns a vector that's size 400. winmain:
int WINAPI WinMain(	HINSTANCE	hInstance,			// Instance
HINSTANCE	hPrevInstance,		// Previous Instance
LPSTR		lpCmdLine,			// Command Line Parameters
int			nCmdShow)			// Window Show State
{
MSG		msg;									// Windows Message Structure
BOOL	done = false;								// Bool Variable To Exit Loop
DR game;                                // Create our game

// Create OpenGL window
if (!CreateGLWindow("Dark Raider",600,600,16,fullscreen))
{
return 0;									// Quit If Window Was Not Created
}

while(!done)									// loop until done == true
{
if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
{
if (msg.message==WM_QUIT)				// if received quit msg
{
done = true;						// then set done = true
}
else									// If Not, Deal With Window Messages
{
TranslateMessage(&msg);				// Translate The Message
DispatchMessage(&msg);				// Dispatch The Message
}
}
else										// If There Are No Messages
{
// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
if ((active && !game.DrawScene()) || keys[VK_ESCAPE])	// Active?  Was There A Quit Received?
{
done=true;							// ESC or DrawGLScene Signalled A Quit
}
else									// Not Time To Quit, Update Screen
{
SwapBuffers(hDC);					// Swap Buffers (Double Buffering)
}
}
}

// Shutdown
KillGLWindow();									// Kill The Window
return (msg.wParam);							// Exit The Program
}


Any help would be appreciated.. Thanks.

Share on other sites
I couldn't see that you let the process sleep anywhere. If nothing very much interesting is happening, you could add Sleep(1); in the standard-loop where not much happens.

Share on other sites
You're main loop is just looping constantly. As soon as it fiunishes one iteration, it goes on to the next. Obviously you are not giving anything back to the OS. You can use a sleep call or something to give a bit back. However, a full screen game probably should be using as much resources as possible, especially if it will be run on slower hardware.

Share on other sites
From what I hear it normal but what happens if you set the frame rate at max 32 ms?
...DWORD start_time, curr_time;start_time = curr_time = GetTickCount();...curr_time = GetTickCount();if(curr_time - start_time > 32){  if ((active && !game.DrawScene()) || keys[VK_ESCAPE])  {    done=true;  }  else  {    SwapBuffers(hDC);  }}...

I have a similar project that runs with 50% cpu with this setup

Share on other sites
Quote:
 Original post by _0D_0AI couldn't see that you let the process sleep anywhere. If nothing very much interesting is happening, you could add Sleep(1); in the standard-loop where not much happens.

Well, if you're in the foreground, and full screen, you'll want to have 100% of the CPU, or as much of it as possible. Sleep can work a little, but really isn't what I prefer.

As I see it though, your program is always active unless it quits, so its always going to draw, even if you move it into the background.

If you minimize the window, or move it into the background, you should wait for a message

Share on other sites
Quote:
 Original post by pulpfistFrom what I hear it normal but what happens if you set the frame rate at max 32 ms?...DWORD start_time, curr_time;start_time = curr_time = GetTickCount();...curr_time = GetTickCount();if(curr_time - start_time > 32){ if ((active && !game.DrawScene()) || keys[VK_ESCAPE]) { done=true; } else { SwapBuffers(hDC); }}...I have a similar project that runs with 50% cpu with this setup

All that will accomplish is slowing down the framerate. The CPU usage will still be 100% since the loop ois just ging as fast as it can. If there is any reason he CAN'T have 100% CPU (maybe to be nice to laptop users, for instance), then a sleep call is the only way.

The reason your CPU is at 50% means you havea Pentium 4 with Hyperthreading enabled, a dual core processor, or some other CPU intensive program is running in the background.

Sleep is a kinda unreliable call. Sleep(1) basically says "Tell the OS to do something else for AT LEAST 1 millisecond." It could be 1 ms, it could be 10. I would not base anything to important off of this time.

Edit: A quick note: If your game is taking 100% of the CPU, that means there is nothing else using the CPU. If something else actually needed the CPU constantly, your game would use only 50%. The windows scheduler is decent. When you tell it to sleep and there is nothing else to do, the OS is just going to chill for a while and do nothing. You won't be helping anything except possibly the processor temperature.

Share on other sites
How about a yield call in Windows API? Is there such a thing?

Share on other sites
Quote:
 Original post by pulpfistI guess your right.How about a yield call in Windows API? Is there such a thing?

It is called "Sleep()". Just use that function and pass the number of milliseconds. I have no idea if it is windows only or anything (I'll look it up in a second).

Edit: It does appear to be windows only...

Share on other sites
Quote:
Original post by Sr_Guapo
Quote:
 Original post by pulpfistI guess your right.How about a yield call in Windows API? Is there such a thing?

It is called "Sleep()". Just use that function and pass the number of milliseconds. I have no idea if it is windows only or anything (I'll look it up in a second).

It's Windows only and you shouldn't just pass it a number of MS. Sleep(0) is about the same as a yield. You shouldn't pass anything greater unless you wait for a very long time. Sleep(1) often results in more than 10ms waits, which is completely unacceptable.

EDIT: Also you shouldn't use yield unless you can see you are rendering way too much (>150 FPS, at least). imagine slowing your game down 3% when the user already have low-end hardware.

Share on other sites
Ahh Sleep(0) ofcourse...
I didnt think about that hehe

Share on other sites
Quote:
Original post by CTar
Quote:
Original post by Sr_Guapo
Quote:
 Original post by pulpfistI guess your right.How about a yield call in Windows API? Is there such a thing?

It is called "Sleep()". Just use that function and pass the number of milliseconds. I have no idea if it is windows only or anything (I'll look it up in a second).

It's Windows only and you shouldn't just pass it a number of MS. Sleep(0) is about the same as a yield. You shouldn't pass anything greater unless you wait for a very long time. Sleep(1) often results in more than 10ms waits, which is completely unacceptable.

EDIT: Also you shouldn't use yield unless you can see you are rendering way too much (>150 FPS, at least). imagine slowing your game down 3% when the user already have low-end hardware.

Thank you for the clarification. I knew it was often longer than you specify, but I didn't realize it was that bad...

Share on other sites
"Oh no, I asked my program to keep running a loop as fast as possible, and the CPU runs keeps running my loop"

Sorry for the sarcasm, but what did you expect? When you ask a CPU to run a program, it doesn't say "Ok, but I'll only run at 60% speed, and I want a 45 minute lunch break"
It just does what you ask it to, and at the only speed it knows, which is full speed.

If you want it to use less than 100% CPU, then you need to explicitly tell it to stop processing your app.

However, it is not a problem if you're using 100% CPU. It means that no other process is requesting CPU time. Once another process starts consuming CPU time, it will get its fair share.

So unless there are special circumstances to consider (battery life on laptops, for example, or the need to run other CPU-heavy processes at the same time), it's not a problem. It's only a signal that Windows is smart enough to not waste CPU time. What would otherwise be lost doing nothing, is instead given to your app.

Share on other sites
you seem to forget that some systems (most laptops for example - but also desktop computers) have a cpu-fan that powers up when using much CPU. this gets extremely annoying if you just want to make something simple for example, i hope you got the idea :)

bye!

Share on other sites
Quote:
 "Oh no, I asked my program to keep running a loop as fast as possible, and the CPU runs keeps running my loop"Sorry for the sarcasm, but what did you expect? When you ask a CPU to run a program, it doesn't say "Ok, but I'll only run at 60% speed, and I want a 45 minute lunch break"It just does what you ask it to, and at the only speed it knows, which is full speed.If you want it to use less than 100% CPU, then you need to explicitly tell it to stop processing your app.However, it is not a problem if you're using 100% CPU. It means that no other process is requesting CPU time. Once another process starts consuming CPU time, it will get its fair share.So unless there are special circumstances to consider (battery life on laptops, for example, or the need to run other CPU-heavy processes at the same time), it's not a problem. It's only a signal that Windows is smart enough to not waste CPU time. What would otherwise be lost doing nothing, is instead given to your app.

I think you should save your sarcasm for someone bigger and more scary than us.
Besides, how do you explain that my application, similar to he's, only use 50% CPU?

Share on other sites
Quote:
Original post by pulpfist
Quote:
 "Oh no, I asked my program to keep running a loop as fast as possible, and the CPU runs keeps running my loop"Sorry for the sarcasm, but what did you expect? When you ask a CPU to run a program, it doesn't say "Ok, but I'll only run at 60% speed, and I want a 45 minute lunch break"It just does what you ask it to, and at the only speed it knows, which is full speed.If you want it to use less than 100% CPU, then you need to explicitly tell it to stop processing your app.However, it is not a problem if you're using 100% CPU. It means that no other process is requesting CPU time. Once another process starts consuming CPU time, it will get its fair share.So unless there are special circumstances to consider (battery life on laptops, for example, or the need to run other CPU-heavy processes at the same time), it's not a problem. It's only a signal that Windows is smart enough to not waste CPU time. What would otherwise be lost doing nothing, is instead given to your app.

I think you should save your sarcasm for someone bigger and more scary than us.
Besides, how do you explain that my application, similar to he's, only use 50% CPU?

Quote:
 Original post by Sr_GuapoThe reason your CPU is at 50% means you have a Pentium 4 with Hyperthreading enabled, a dual core processor, or some other CPU intensive program is running in the background.

Share on other sites
Its ok Gaupo. No worries here, just got carried away...

Share on other sites
Quote:
 Original post by pulpfistI think you should save your sarcasm for someone bigger and more scary than us.Besides, how do you explain that my application, similar to he's, only use 50% CPU?

Nah, being sarcastic towards scary people is just asking for trouble... [wink]
Cheer up though, a bit of sarcasm doesn't mean I don't wuv you... [lol]
Even if you're not scary

Share on other sites
Anyone who thinks its ok for a program to use 100% CPU for no reason just because it is a game is living in the wrong decade. That was totally acceptable when using DOS extensions on Windows 95, and was the normal practice throughout the life of the Win 9x series of operating systems. But today there are many reasons why it is very bad form.

1) Modern computers do not require full utilization to run most games, therefore a significant percentage of people run other applications in the background (downloads, music players, servers, chat clients, team speak, etc).
2) Getting a "fair slice" is not the same as getting the available amount. If 3 apps are running all with this mentality, then each can only ever get 1/3rd the CPU power (ignoring overhead). With todays increasingly pervasive multithreading, this becomes more and more of an issue.
3) Power usage and heat ARE relevant. Most computers built today are not actually designed to run at maximum usage with maximum graphics, audio, and IO usage and cannot actually maintain that level of power draw and heat indefinately. Most computers can manage just 100% CPU at all times, but once the graphics cards and DVDs get involved they begin to cross their threashold of stability.
4) Most games can be played perfectly well on laptops, and soon will begin to be playedmore and more on tablets and ultralights. This is especially true for the increasing market of casual games selling like hotcakes at \$20 a pop.

So, while any FPS style games caring about latency will full-well expect your app to use 100% power at all times (and they should) a player of Civ IV or Chessmaster most likely will not.

Share on other sites
Quote:
 Original post by Spoonbender"Oh no, I asked my program to keep running a loop as fast as possible, and the CPU runs keeps running my loop"Sorry for the sarcasm, but what did you expect? When you ask a CPU to run a program, it doesn't say "Ok, but I'll only run at 60% speed, and I want a 45 minute lunch break"It just does what you ask it to, and at the only speed it knows, which is full speed.If you want it to use less than 100% CPU, then you need to explicitly tell it to stop processing your app.However, it is not a problem if you're using 100% CPU. It means that no other process is requesting CPU time. Once another process starts consuming CPU time, it will get its fair share.So unless there are special circumstances to consider (battery life on laptops, for example, or the need to run other CPU-heavy processes at the same time), it's not a problem. It's only a signal that Windows is smart enough to not waste CPU time. What would otherwise be lost doing nothing, is instead given to your app.

I don't get it.
If what you say is true, then how come playing Windows 3d pinball doesn't use 100% cpu?
With pinball opened, it only says '6%' under window task manager, and the rest is system idle process.
For world of warcraft, it runs at around 85% cpu...compare to my game that only draws a tile map runs at 100%.
Ummmm...

If the CPU runs @ 100% all the time, wouldnt the temp be too high?
I always though CPUs just allocate whatever is needed for an app, and save the rest of resource..

Share on other sites
There is a way to enable vsynch, so your game will only update every frame (instead of updating x times a frame). This will also reduce the cpu time quite a bit, since your game will be waiting for the next frame to update. To me, this makes more sense, since you need at least some spare time for background tasks like garbage collection (Java, C#), or at the very least the usual OS tasks need some %.

Share on other sites
Quote:
 Original post by ShowI don't get it.If what you say is true, then how come playing Windows 3d pinball doesn't use 100% cpu?With pinball opened, it only says '6%' under window task manager, and the rest is system idle process.For world of warcraft, it runs at around 85% cpu...compare to my game that only draws a tile map runs at 100%.Ummmm...If the CPU runs @ 100% all the time, wouldnt the temp be too high?I always though CPUs just allocate whatever is needed for an app, and save the rest of resource..

The reason why pinball doesn't use that much of the CPU, is the program is telling the computer that it doesn't need that many resources. It only updates once every x milliseconds.

On the other hand, even if you think you have only one triangle, it is possible to use 100% of the CPU. If you don't cap what you're displaying, or use an intelligent algorithm, the computer basically looks at the situation and says

Hey, I have one triangle and was told to run this continuously.

So that's what it does. It runs that one triangle at 3500 frames per second using every spare CPU clock cycle, because that's what you told it to do.

I know I mentioned that you should be using close to 100% of the CPU clock cycle, because I made a few assumptions about what you're trying to do. Other people mentioned its not always a smart idea. And we're both right to a certain degree. You need to use as much of the computer as you feel is necessary.

If you get 1000+ fps, maybe you can lay off the CPU some, and save the battery life. On the other hand, if you're running at 2 fps at 10% CPU intake, maybe you want to increase it.

Share on other sites
I personally write my programs to use up to 100% CPU usage, but not moer than necessary to maintain a certain framerate (30 for non-real time / twitch games and usually whatever the refreash of the monitor is for twitch games -like first person shooters)

Of course for cutting edge games with realistic physics and intelligent AI you WILL use 100% CPU all the time, cause your going to be doing the most you can all the time. I was simply trying to say that being a game is not enough in itself to justify that attitude. You really need to be an action real-time game before you adopt the attitude that the system is yours to abuse at will.

Of course each method of using less than 100% CPU has tradoffs, so there is no one-size-fits-all solution to this problem.

Share on other sites
I have a question. I was under the impression that the CPU constantly executes instructions whenever it's on. I thought that it being idle just meant that it is in a busy-wait loop.

But if that's true, then a program running at 100% would not affect the battery or fan; it would just take time from other processes.

So does the CPU actually stop executing when it's idle?

Share on other sites
It doesn't really stop, but modern processors can be made to slow down (see SpeedStep).

Also, executing idle instructions is potentially easier on the processor, because signals (except the clock) aren't changing as often. CMOS logic draws much more power to change a signal than it does to keep it steady (even if 'high').

Share on other sites
Its very similar to the difference in your video card between running just a windows desktop, running a 3d program, and running a 3d program that uses all the technology (shaders, etc). The areas of the chip that are not in use are usually using almost no power and generating almost no heat.

A chip these days is a lot like a house where, at any given time not every light or outlet is in use - but there is at least a certain minimum amount of power being consumed at all times. And more advance technologies let chips completely turn off whole areas of the chip while not in use (like closing off rooms and vents in a guest room to conserve heating and cooling bill).