## Best way to calculate framerate

Moderator
Posts: 3,567
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.
Luminary
Posts: 5,139
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...
Moderator
Posts: 768
Joined: 2003.04
Post: #18

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.
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.