Calculating frames per second in a game

后端 未结 19 693
天命终不由人
天命终不由人 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:55

    Well, certainly

    frames / sec = 1 / (sec / frame)
    

    But, as you point out, there's a lot of variation in the time it takes to render a single frame, and from a UI perspective updating the fps value at the frame rate is not usable at all (unless the number is very stable).

    What you want is probably a moving average or some sort of binning / resetting counter.

    For example, you could maintain a queue data structure which held the rendering times for each of the last 30, 60, 100, or what-have-you frames (you could even design it so the limit was adjustable at run-time). To determine a decent fps approximation you can determine the average fps from all the rendering times in the queue:

    fps = # of rendering times in queue / total rendering time
    

    When you finish rendering a new frame you enqueue a new rendering time and dequeue an old rendering time. Alternately, you could dequeue only when the total of the rendering times exceeded some preset value (e.g. 1 sec). You can maintain the "last fps value" and a last updated timestamp so you can trigger when to update the fps figure, if you so desire. Though with a moving average if you have consistent formatting, printing the "instantaneous average" fps on each frame would probably be ok.

    Another method would be to have a resetting counter. Maintain a precise (millisecond) timestamp, a frame counter, and an fps value. When you finish rendering a frame, increment the counter. When the counter hits a pre-set limit (e.g. 100 frames) or when the time since the timestamp has passed some pre-set value (e.g. 1 sec), calculate the fps:

    fps = # frames / (current time - start time)
    

    Then reset the counter to 0 and set the timestamp to the current time.

提交回复
热议问题