Calculating frames per second in a game

后端 未结 19 767
天命终不由人
天命终不由人 2020-12-04 05:10

What\'s a good algorithm for calculating frames per second in a game? I want to show it as a number in the corner of the screen. If I just look at how long it took to render

19条回答
  •  囚心锁ツ
    2020-12-04 05:34

    Here's how I do it (in Java):

    private static long ONE_SECOND = 1000000L * 1000L; //1 second is 1000ms which is 1000000ns
    
    LinkedList frames = new LinkedList<>(); //List of frames within 1 second
    
    public int calcFPS(){
        long time = System.nanoTime(); //Current time in nano seconds
        frames.add(time); //Add this frame to the list
        while(true){
            long f = frames.getFirst(); //Look at the first element in frames
            if(time - f > ONE_SECOND){ //If it was more than 1 second ago
                frames.remove(); //Remove it from the list of frames
            } else break;
            /*If it was within 1 second we know that all other frames in the list
             * are also within 1 second
            */
        }
        return frames.size(); //Return the size of the list
    }
    

提交回复
热议问题