OpenGL Programming/Performances

When to optimize

A common pitfall is to be obsessed with optimization, to the point of spending a lot of coding time on tiny optimization, while complexifying the code and making it harder to debug.

Make sure you optimize when you have evidence that the impacted code truly slows down the application. Make measurements. Compare in different use cases and possibly different hardware.

Also, we recommend that when implementing a new feature, you write your first version as clear as possible, and optimize it in a second step when the feature works correctly.

Measuring frames per second (FPS)

FPS are a simple way to measure performances. You can easily get tangible proof of your optimization and measure the performance increase (or decrease!). It is more reliable than your intuitive feeling of "smoothness" when testing your application.

Here's a simple code to display the FPS once per second on the console:

/* Global */
static unsigned int fps_start = 0;
static unsigned int fps_frames = 0;
/* init_resources() */
  fps_start = glutGet(GLUT_ELAPSED_TIME);
/* idle() */
  /* FPS count */
  {
    fps_frames++;
    int delta_t = glutGet(GLUT_ELAPSED_TIME) - fps_start;
    if (delta_t > 1000) {
      cout << 1000.0 * fps_frames / delta_t << endl;
      fps_frames = 0;
      fps_start = glutGet(GLUT_ELAPSED_TIME);
    }
  }

Vertical sync

Often, OpenGL is configured to wait for the physical screen's vertical refresh before pushing the new color buffer:

  • this prevents tearing, a visual artifact that mixes part of the previous buffer with part of the new one
  • there is no visual need to display more frames than what the screen can handle, typically 60-75Hz (depending on the screen)
  • this saves resources such as the battery

However, this means that even if we can display 200 FPS, our application will be capped to 60-75 FPS, which makes it difficult to measure the performances.

In such case, it can be useful to disable the vertical sync:

  • your graphic card driver may come with utilities to enable and disable it
  • with Mesa, you can start your application with vblank_mode=0, or configure this behavior more permanently in ~/.drirc; some earlier versions have bugs, so you may have to try both.

Stencil buffer tests

See performances tips in the Stencil buffer section.

- Comment on this page

- Recent stats

< OpenGL Programming

Browse & download complete code
Last modified on 30 April 2013, at 14:45