Page 1 of 1

Is there a proper way to calculate frame rate?

Posted: December 23rd, 2019, 4:18 am
by WilsonHuang
The following code is how I calculate frame rate:

Code: Select all

[Game.h]
FrameTimer ft;
float totalFrameTime = 0.0f;
int frameCounter = 0;
float fps = 0.0f;

[Game.cpp]
void Game::Go()
{
	gfx.BeginFrame();	
	UpdateModel();
	ComposeFrame();
	gfx.EndFrame();
	frameCounter += 1;
}

void Game::UpdateModel()
{
	totalFrameTime += ft.GetFrameTime();
	fps = frameCounter / (totalFrameTime / 1.0f);
	std::wstringstream stream;
	stream << std::setprecision(4) << fps;
	wnd.SetWindowTitle(stream.str());
}
I notice a problem is that if I don't close the problem, the two variables "frameCounter" and "totalFrameTime" will be overflow one day.
How do I prevent this? Or is there a proper way to calculate frame rate? Any advice is welcome!

Re: Is there a proper way to calculate frame rate?

Posted: December 23rd, 2019, 4:53 am
by albinopapa
Well, your frame count will overflow way before the total frame time, but the easiest way would be to just reset the time and count every so often. Maybe every 10 seconds or every 1,000 frames.

You could also switch to using a uint64_t type ( the built in type or intrinsic type would be unsigned long long ) which would count to ‭‭18,446,744,073,709,551,616‬ before needing to roll back to 0.

Assuming 60 frames per second, you could get this to run for
‭9,749,040,289.251200541180449856249‬ years and never have rollover.

You'd also probably want to change the float totalFrameTime to a double totalFrameTime to maintain precision.

Re: Is there a proper way to calculate frame rate?

Posted: December 23rd, 2019, 5:08 am
by WilsonHuang
albinopapa wrote:
December 23rd, 2019, 4:53 am
Well, your frame count will overflow way before the total frame time, but the easiest way would be to just reset the time and count every so often. Maybe every 10 seconds or every 1,000 frames.

You could also switch to using a uint64_t type ( the built in type or intrinsic type would be unsigned long long ) which would count to ‭‭18,446,744,073,709,551,616‬ before needing to roll back to 0.

Assuming 60 frames per second, you could get this to run for
‭9,749,040,289.251200541180449856249‬ years and never have rollover.

You'd also probably want to change the float totalFrameTime to a double totalFrameTime to maintain precision.
Thanks for your advice, I'll take that.