logoalt Hacker News

mightyhamtoday at 12:54 PM1 replyview on HN

If all you care about is a windowed average you can implement the fps counter (really you keep track of seconds per frame) using an exponential moving average which has constant time and space complexity regardless of window size. The calculation you do once a frame is:

spf_avg = alpha * cur_spf + (1.0f - alpha) * spf_avg;

For alpha value you can use the formula:

alpha = 2/(n+1)

Which will give smoothing comparable to an n sample moving average. This is the same formula used for n-day exponential moving averages for stocks.

As the article points out, this is a sample based window which is not as good as a time based window, but it's also dead simple to implement. Maybe someone smarter than me knows how to derive a formula for exponential moving average for time based windows.


Replies

spacechild1today at 1:27 PM

That's basically a one-pole low pass filter. You can use this for smoothing any kind of data that arrives at a steady rate.

You can also dynamically calculate the filter coefficient based on the current delta time, which makes sure that the smoothing behavior is independent from the current framerate.

show 1 reply