What is the preferred way to get the frame rate of a JavaFX application?

This is a very simple question:

What is the preferred way to get the frame rate of a JavaFX application?

Google showed results in 2009, but this example is similar to JavaFX 1 X is relevant and starts operating in a strange way (some kind of external instrument) I can't find a better example. I post here

I want to be able to query my JavaFX application (or, if necessary, the current scenario) and get the current FPS

Updated: February 8, 2015

Various solutions to this problem are published below as answers I also found that this problem was cited by the following blog posts: http://tomasmikula.github.io/blog/2015/02/08/measuring-fps-with-reactfx.html

Which said (due to the level of detail of the following solution) that the measured FPS was added to reactfx 2.0 milestone 2 Cool the way things spread

Solution

You can use animationtimer

The handle method of animationtimer is called once per frame, and the value passed in is the current time in nanoseconds (the best approximation) Therefore, you can track the time since the last frame

This is an implementation that tracks the time of the last 100 frames and uses them to calculate the frame rate:

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class SimpleFrameRateMeter extends Application {

    private final long[] frameTimes = new long[100];
    private int frameTimeIndex = 0 ;
    private boolean arrayFilled = false ;

    @Override
    public void start(Stage primaryStage) {

        Label label = new Label();
        AnimationTimer frameRateMeter = new AnimationTimer() {

            @Override
            public void handle(long Now) {
                long oldFrameTime = frameTimes[frameTimeIndex] ;
                frameTimes[frameTimeIndex] = Now ;
                frameTimeIndex = (frameTimeIndex + 1) % frameTimes.length ;
                if (frameTimeIndex == 0) {
                    arrayFilled = true ;
                }
                if (arrayFilled) {
                    long elapsedNanos = Now - oldFrameTime ;
                    long elapsedNanosPerFrame = elapsedNanos / frameTimes.length ;
                    double frameRate = 1_000_000_000.0 / elapsedNanosPerFrame ;
                    label.setText(String.format("Current frame rate: %.3f",frameRate));
                }
            }
        };

        frameRateMeter.start();

        primaryStage.setScene(new Scene(new StackPane(label),250,150));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>