Search code examples
c++sdlframe-rate

Am I calculating my FPS correctly?


So I was wondering if I'm calculating my FPS correctly:

Uint32 delayFrom(float startTime, float endTime){
    return(endTime - startTime );
}


int main(){
    int numFrames = 0;
    Uint32 startTime = SDL_GetTicks();
    while(!done){
        frameTime = 0;
        float fps = ( numFrames/(float)(SDL_GetTicks() - startTime) )*1000;
        cout << fps << endl;
        SDL_Delay(delayFrom(frameTime, 1/60));
        ++numFrames;
    }
}

Solution

  • int main() {
      int numFrames = 0;
      Uint32 startTime = SDL_GetTicks();
      while (!done) {
        ++numFrames;
        Uint32 elapsedMS = SDL_GetTicks() - startTime; // Time since start of loop
        if (elapsedMS) { // Skip this the first frame
          double elapsedSeconds = elapsedMS / 1000.0; // Convert to seconds
          double fps = numFrames / elapsedSeconds; // FPS is Frames / Seconds
          cout << fps << endl; 
        }
        SDL_Delay(1.0/60.0); // Use floating point division, not integer
      }
    }