'Displaying FPS in GLFW window title?

Im trying to get my FPS to display in the window title but my program is just not having it.

my FPS code

    void showFPS()
{
     // Measure speed
     double currentTime = glfwGetTime();
     nbFrames++;
     if ( currentTime - lastTime >= 1.0 ){ // If last cout was more than 1 sec ago
         cout << 1000.0/double(nbFrames) << endl;
         nbFrames = 0;
         lastTime += 1.0;
     }
}

and i want it too go just after the Version here

window = glfwCreateWindow(640, 480, GAME_NAME " " VERSION " ", NULL, NULL);

but i cant just call the void i i have to convert it too a char ? or what ?



Solution 1:[1]

void showFPS(GLFWwindow *pWindow)
{
    // Measure speed
     double currentTime = glfwGetTime();
     double delta = currentTime - lastTime;
     nbFrames++;
     if ( delta >= 1.0 ){ // If last cout was more than 1 sec ago
         cout << 1000.0/double(nbFrames) << endl;

         double fps = double(nbFrames) / delta;

         std::stringstream ss;
         ss << GAME_NAME << " " << VERSION << " [" << fps << " FPS]";

         glfwSetWindowTitle(pWindow, ss.str().c_str());

         nbFrames = 0;
         lastTime = currentTime;
     }
}

Just a note, cout << 1000.0/double(nbFrames) << endl; wouldn't give you "frame-per-second" (FPS), but would give you "milliseconds-per-frames" instead, most likely 16.666 if you are at 60 fps.

Solution 2:[2]

Have you considered something like this?


void
setWindowFPS (GLFWwindow* win)
{
  // Measure speed
  double currentTime = glfwGetTime ();
  nbFrames++;

  if ( currentTime - lastTime >= 1.0 ){ // If last cout was more than 1 sec ago
    char title [256];
    title [255] = '\0';

    snprintf ( title, 255,
                 "%s %s - [FPS: %3.2f]",
                   GAME_NAME, VERSION, 1000.0f / (float)nbFrames );

    glfwSetWindowTitle (win, title);

    nbFrames = 0;
    lastTime += 1.0;
  }
}

Solution 3:[3]

There's always the stringstream trick:

template< typename T >
std::string ToString( const T& val )
{
    std::ostringstream oss;
    oss << val;
    return oss.str();
}

Or boost.lexical_cast.

You can use std::string::c_str() to get a null-terminated string to pass in to glfwSetWindowTitle().

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Andon M. Coleman
Solution 3