Processor Greed

We’ve been getting some feedback from users playing our game that their systems’ processors spike to 100% while running the game. It then stays up there even when the app is hidden. It’s causing powerbooks to run rather hot.

Is this a usual occurance with Unity-built projects (I never really noticed it on my machine, but I’m running a G5)? And is there anything I can do to make the app less processor hungry?

If it helps, there’s a build of it available at:

http://redrovergames.com/scramble/scrambledMAC.zip

Thanks,
-rob

In trying to get as high framerates as opossible, 3D engines will generally use all the processor power they can get.

First: by default Unity pauses in the background. To make sure it does, uncheck “Run in background” in the player settings ( http://unity3d.com/Documentation/Components/class-PlayerSettings.html )

Second: in the case when you want fewer frames per second, someone came up with a method to sleep a few milliseconds during each frame, to force Unity not to go above some number of frames per second. Jonathan Czeck just told me that you should do this:

import System.Threading;
Thread.Sleep(milliseconds);

The trick is to calculate how many milliseconds so as to limit the framerate only if it’s “too high”.

d.

This quick script seems to work okay, but the calculation could probably be made a lot better. :slight_smile:

import System.Threading;

var goalFPS = 30;
	
private var millisecondsToWait = 0;
	
function Update ()
{
	var overflow = 1.0/goalFPS - Time.deltaTime;
	if (overflow > 0.0)
		millisecondsToWait ++;
	else
		millisecondsToWait --;
	
	Thread.Sleep(Mathf.Clamp(millisecondsToWait, 0.0, 1.0/goalFPS * 1000.0)); // clamp for sanity		
}

-Jon

Thanks for the input.

We have our game set to run in the background in order to prevent cheating (it’s a timer-based word game). However, I believe that there’s a way to access the runinbackground variable from the script so at least I can turn it to false while in menus or paused.

I’m going to try the script Jonathan provided and see if that affects anything.

Thanks again,
-Rob

Well, that worked beautifully. We were able to relinquish about 80% of the processor load by capping Unity at around 60 fps.

Thanks guys!

-rob

That’s great to know! It seems especially appropriate for Scrambled type games.

-Jon

Seems like a good script for the wiki.

Oh, and dynamically setting the runInBackground toggle worked nicely, too. During any time where the timer is inactive (menu screens, paused, or non-timed game modes) we have the app turn off runInBackground which makes our app use a measly 2-5% processor on our test MacBook Pro.

Ahhhh, I love a productive day : )

-rob

Stupid question maybe, but where should Jonathan’s script be put?
Should it be attached to just an object in the Hierarchy?

Yes. Attach to any game object.