# Game Loop, calculate the Frames Per Second.

• June 20th, 2012, 04:21 AM
Dirk94
Game Loop, calculate the Frames Per Second.
Ok, so first of all I would like to say that I'm still very 'Noob-ish' when it comes to programming in Java.

I'm creating a simple game, however I thought it would be a nice challenge to display the frames per second in my game.
But all the articles about it are really complex (for me) , and nobody seems to have a game loop the way I do.
This is what my game loop looks like:

My Main class extends the JPanel
Code :

` public class Main extends JPanel {`

Also in my main class the game loop, it uses the default repaint() method. In wich I draw all the images etc.
Code :

```public void run() { while (true) { long time = System.currentTimeMillis();   repaint();   time = (1000 / Globals.maxFPS) - (System.currentTimeMillis() - time);   if (time > 0) { try { Thread.sleep(time); } catch (Exception e) } } } }```

My first thought was to calculate the FPS using the time variable, however no mather how slow the game goes time is always 16. So I realy don't understand how I should calculate the FPS in this game loop.

If you need any more information I'll be happy to give it :)

Dirk
• June 20th, 2012, 07:30 AM
KevinWorkman
Re: Game Loop, calculate the Frames Per Second.
There are a couple ways to do this.

Each frame, calculate the time (in seconds) it has been since the last frame. Divide 1 by that number, and that's your momentary fps.

Do a similar calculation, only spread out over more time- every x number of frames, calculate how long it's been since the last x frames. Take x divided by that time, and that's your fps.

Or do it the other way around- every second, calculate how many frames have passed. That's your fps. Or every 5 seconds, divided by 5.
• June 20th, 2012, 07:35 AM
Norm
Re: Game Loop, calculate the Frames Per Second.
Quote:

it uses the default repaint() method. In wich I draw all the images etc.
Do you have a repaint() method with your code in it? That is not normal and I don't know how it would work.
The call to the repaint() method will return without much delay.
(System.currentTimeMillis() - time) will be 0 most of the time.

I'm not sure I understand your problem. Where is the FPS value shown?