Search code examples
javaframe-rate

Making a FPS shower?


I am trying to make a string with FPS showing, but, how do I actually get my programs FPS? I want to do it with

g.drawString(getFPS(), 10, 10)

How do I get my FPS?


Solution

  • This code does it for me. Put it in your main program loop:

    //To Measure FPS
    private long now;
    private int framesCount = 0;
    private int framesCountAvg=0; 
    private long framesTimer=0;
    
    //Main Game Loop
        while (isRunning)
        {
            //Record the time before update and draw
            long beforeTime = System.nanoTime();
            //... Update program & draw program...
            // DRAW FPS: 
            now=System.currentTimeMillis(); 
            gEngine.drawFPS(c, framesCountAvg);
            framesCount++; 
            if(now-framesTimer>1000)
            { 
                  framesTimer=now; 
                  framesCountAvg=framesCount; 
                  framesCount=0; 
            }}
    

    that call "gEngine.drawFPS" just tells my main draw method to include the fps at the top of the screen (and c is my Canvas) - you can use a similar method to give your "g" class the correct framesCountAvg data to draw