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

后端 未结 3 1549
梦谈多话
梦谈多话 2020-12-17 00:08

This is quite a simple question:

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

Google turns up a result from 2009, but that e

3条回答
  •  长情又很酷
    2020-12-17 00:48

    James_D gave a naive implementation that gives the instantaneous FPS and he suggested a more sophisticated approach. My attempt at that is the following:

    public class FXUtils
    {
        private static long lastUpdate = 0;
        private static int index = 0;
        private static double[] frameRates = new double[100];
    
        static
        {
            AnimationTimer frameRateMeter = new AnimationTimer()
            {
                @Override
                public void handle(long now)
                {
                    if (lastUpdate > 0)
                    {
                        long nanosElapsed = now - lastUpdate;
                        double frameRate = 1000000000.0 / nanosElapsed;
                        index %= frameRates.length;
                        frameRates[index++] = frameRate;
                    }
    
                    lastUpdate = now;
                }
            };
    
            frameRateMeter.start();
        }
    
        /**
         * Returns the instantaneous FPS for the last frame rendered.
         *
         * @return
         */
        public static double getInstantFPS()
        {
            return frameRates[index % frameRates.length];
        }
    
        /**
         * Returns the average FPS for the last 100 frames rendered.
         * @return
         */
        public static double getAverageFPS()
        {
            double total = 0.0d;
    
            for (int i = 0; i < frameRates.length; i++)
            {
                total += frameRates[i];
            }
    
            return total / frameRates.length;
        }
    }
    

提交回复
热议问题