Doing Doing this with 1000 / elapsed_time is not a 100% accurate because of it's limited to 1000 fps or we get an division by zero and we infact do not actually show the fps but only a mathematical approximation. What you can do is have a check performed if the elapsed time is zero then output "+1000 FPS".
I don't like this method as the framerate will jump a lot every frame. And it makes it completly unreadable. I prefer what you do because the framerate is 100% accurate and it is only updated once every second mmaking it readable.
My code for it is:
#include <GDE/RuntimeDisplayer.hpp>
#include <GDE/GDE.hpp>
#include <GDE/Macros.hpp>
#ifdef _WIN32
#include <windows.h>
#include <psapi.h>
#else
#error Have not been defined for target operating system!
#endif
static sf::Text localFPSText( "0 FPS", sf::Font::GetDefaultFont(), 15 );
static sf::Text localMemoryText( "0/0 Bytes", sf::Font::GetDefaultFont(), 15 );
static sf::Uint32 localFrameCounter = 0;
static sf::Uint32 localFrameTime = 0;
static sf::Uint32 localFPS = 0;
namespace GDE
{
namespace RuntimeDisplayer
{
void Init();
void MemoryUsage( sf::Uint64 &someUsedMemory, sf::Uint64 &someAllocatedMemory );
}
}
void GDE::RuntimeDisplayer::Init()
{
localFPSText.SetPosition( 5, 5 );
localMemoryText.SetPosition( 5, 25 );
localFPSText.SetColor( sf::Color::Yellow );
localMemoryText.SetColor( sf::Color::Yellow );
}
void GDE::RuntimeDisplayer::MemoryUsage( sf::Uint64 &someUsedMemory, sf::Uint64 &someAllocatedMemory )
{
PROCESS_MEMORY_COUNTERS memoryData;
assert( GetProcessMemoryInfo( GetCurrentProcess(), &memoryData, sizeof( memoryData ) ) == TRUE );
someUsedMemory = memoryData.WorkingSetSize;
someAllocatedMemory = memoryData.PagefileUsage;
}
void GDE::RuntimeDisplayer::Update( const sf::Uint32 someTime )
{
localFrameCounter += 1;
localFrameTime += someTime;
if( localFrameTime >= 1000 )
{
localFPS = localFrameCounter;
localFrameCounter = 0;
localFrameTime -= 1000;
localFPSText.SetString( GDE::ConvertToString( localFPS ) + " FPS" );
sf::Uint64 usedMemory = 0;
sf::Uint64 allocatedMemory = 0;
GDE::RuntimeDisplayer::MemoryUsage( usedMemory, allocatedMemory );
localMemoryText.SetString( GDE::ConvertToString( static_cast< float >( usedMemory / 1024 ) / 1024.f ) + "/" + GDE::ConvertToString( static_cast< float >( allocatedMemory / 1024 ) / 1024.f ) + " Megabytes" );
}
}
void GDE::RuntimeDisplayer::Render( sf::RenderTarget &aTarget )
{
sf::View oldView = aTarget.GetView();
aTarget.SetView( aTarget.GetDefaultView() );
aTarget.Draw( localFPSText );
aTarget.Draw( localMemoryText );
aTarget.SetView( oldView );
}
Feel free to use it, it does the same thing except that it will also display the current use of memory and how much has been allocated by the system. You can comment that out if not interested ^^