Page 1 of 1

Let's find a way to limit the CPU usage in games.

Posted: Thu Mar 10, 2005 5:43 pm
by Joakim Christiansen
My example. (don't run directly from the zip file)
In my example I used this code to limit the CPU usage without causing any lagg:

Code: Select all

timeDelay = ElapsedMilliseconds() - masterTimer
masterTimer = ElapsedMilliseconds()
If timeDelay < 11
  Delay(11 - timeDelay)
EndIf
Without this code the CPU usage was constant 100%, with it was ca.0-8%.
But how can I convert this to frame rate, if I want it to run at 85 or 60 fps?

I searched the forum for other posts about this.
And I noticed in one of Psychophanta's posts that he said this:
I've noticed that ALL the time used when the FlipBuffers() function WAITS FOR actually swap the screen buffers seems to be wasting CPU resources, what is innecessary. So, if that is true, it is sure that the FlipBuffers() function need to be modified.
And i'm 100% agree with him.

Feel free to post your own code snippets to limit the CPU usage.

Edit: I noticed I could change 11 to 15 without causing any lagg, but it lagged a little on 16...

Posted: Thu Mar 10, 2005 10:16 pm
by dracflamloc
one (ugly) way to do it is something like:

Code: Select all

desiredFPS=60
FPSDelay=1000/desiredFPS

Repeat
  ;do drawing here and such
  Delay(FPSDelay)
Until event=#PB_EVENT_CLOSE (or whatever)

Posted: Fri Mar 11, 2005 3:30 am
by Joakim Christiansen
Thank you!

I have noticed something weird...

Code: Select all

InitKeyboard():InitSprite()
SetRefreshRate(60)
OpenScreen(640,480,16,"Test")
;SetFrameRate(60)

CreateSprite(0,32,32)
StartDrawing(SpriteOutput(0))
  Circle(15,15,15,RGB(255,0,0))
StopDrawing()

x.l = 64
dir.b

fps.l
num_frames.l
lst_second.l = ElapsedMilliseconds()

Repeat
  FlipBuffers()
  ClearScreen(0,0,0)
  
  If dir = 0
    x + 5
  Else
    x - 5
  EndIf
  
  If x > 544
    dir = 1
  ElseIf x < 64
    dir = 0
  EndIf
  
  DisplaySprite(0,x,240)
  
  StartDrawing(ScreenOutput())
    DrawingMode(1)
    Locate(5,5)
    FrontColor(255,255,255)
    DrawText("FPS: "+Str(fps))
  StopDrawing()
  
  num_frames+1
  If ElapsedMilliseconds()-lst_second >= 1000
      fps = num_frames
      num_frames = 0
      lst_second+1000
  EndIf
  ExamineKeyboard()
Until KeyboardPushed(#PB_Key_Escape)
That works fine, no lagg and 60 fps.

But if I change the start to this:

Code: Select all

InitKeyboard():InitSprite()
;SetRefreshRate(60)
OpenScreen(640,480,16,"Test")
SetFrameRate(60)
Then it would lagg...