Best way to calculate framerate

Moderator
Posts: 3,579
Joined: 2003.06
Post: #16
kelvin Wrote:You've got a divide by zero error waiting to happen on fast machines.

Note: this goes for all the above implementations in this thread. (except mine of course)
Only if they're so fast that they can warp back in time one second (or a half second in my implementation). There is a conditional test if (elapsed > 1.0) preventing such an occurrance in the example you clipped.
Quote this message in a reply
Luminary
Posts: 5,143
Joined: 2002.04
Post: #17
My code always looks something like this:

Code:
static unsigned frame_count = 0;
    static double last_fps_time = -1.0;
    
    static double last_frame_time = -1.0;
    if (last_frame_time < 0.0)
    {
        last_frame_time = time_now();
        last_fps_time = last_frame_time;
    }
    double now = time_now();
    double dt = now - last_frame_time;
    last_frame_time = now;
    
    double dt_fps = now - last_fps_time;
    if (dt_fps > 1.0)
    {
        printf("%0.2f fps\n", frame_count / dt_fps);
        frame_count = 0;
        last_fps_time = now;
    }
    ++frame_count;

You don't want to update your FPS display every frame; it'll just be unreadable. Once a second is plenty. This gives an average over the second, once a second, approximately. It gives readable results with a minimum of effort.

If you're looking for sharp dips in framerate due to specific events, you'll want something more accurate -- but then you'll want statistics on each and every frame, correllated with certain kinds of events, too...
Quote this message in a reply
Moderator
Posts: 771
Joined: 2003.04
Post: #18
OneSadCookie Wrote:You don't want to update your FPS display every frame; it'll just be unreadable.

I do; that's why the smoothing is there. In particular, I want the decimal part (I usually show just one digit) to be a blur, while the integer part smoothly goes up and down, tracking the actual framerate in real-time yet still being perfectly readable.
Quote this message in a reply
Sage
Posts: 1,199
Joined: 2004.10
Post: #19
kelvin Wrote:You've got a divide by zero error waiting to happen on fast machines.

Note: this goes for all the above implementations in this thread. (except mine of course)

Ehh... the code doesn't perform the divide unless 'elapsed' is greater than one. Am I missing something? Doesn't look like a divide-by-zero to me.
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Framerate control + basic physics math MacGoober 4 3,412 Jan 10, 2007 11:40 AM
Last Post: Frank C.
  Calculate mouse position in opengl MACnus 1 3,724 Nov 8, 2006 01:02 PM
Last Post: akb825
  NSTimer / animation framerate question MonitorFlickers 5 5,234 Dec 4, 2005 01:10 PM
Last Post: MonitorFlickers