Creating an FPS elevator?

I'm trying to make a line showing FPS, but how do I get my FPS programs? I want to do this with

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

How do I get FPS?

+3
source share
3 answers

This code does this for me. Put it in the 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; 
        }}

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

+9
source

Calculate the elapsed time and it 1000/elapsedTimewill be your fps.

+2
source

, . 2011 , OP, , . , , , ( 2 ).

, Java GUI:

public class FrameRateCounter {

    private Map<Long, Long> measurementTimes;


    public FrameRateCounter() {
        measurementTimes = new HashMap<Long, Long>();
    }

    public synchronized void submitReading() {
        long measurementTime = System.nanoTime();
        long invalidationTime = System.nanoTime() + 1000000000;
        measurementTimes.put(measurementTime, invalidationTime);
    }

    public int getFrameRate() {
        performInvalidations();
        return measurementTimes.size();
    }

    private synchronized void performInvalidations() {
        long currentTime = System.nanoTime();
        Iterator<Long> i = measurementTimes.keySet().iterator();
        while(i.hasNext()) {
            long measurementTime = i.next();
            long invalidationTime = measurementTimes.get(measurementTime);
            if(invalidationTime < currentTime) {
                i.remove();
            }
        }
    }
}

( ):

  • - , FPS, " " . , /.
  • GUI - , . - , Graphics JLabel , .
  • , - - - ( O (1)). , .
  • javax.Swing.Timer - submitReading() /, getFrameRate() /, (, JLabel, ..).

(PS .: Note that with Swing, all drawing operations must be populated in the Event Dispatcher (EDT) stream. Therefore, no drawing work should be delegated to other (unprocessed) streams without using special commands such as SwingUtilities.invokeLater(..)).

Hope this helps!

0
source

All Articles