Reputation:
I'm writing my own OpenGL and Win32 library in C, and I'm implementing a function to limit FPS. To do that, I'm firstly writing some code to check if it works and then I will abstract it to functions later. I don't know what's missing but it's not working. Here's my current code and the output
#include "2DM.h"
#include <time.h>
int main(void) {
WINDOW window = createWindow("WINDOW", 500, 500, WINDOW_NORMAL);
const int FPS_LIMIT = 60;
int initialTime = time(NULL), finalTime, frameCount = 0;
while(window.open) {
if(pollEvents(&window) {
/*
* Events handling
* .........
*/
}
/*
* OpenGL code
* .........
*/
display(&window);
frameCount ++;
finalTime = time(NULL);
int ellapsedTime = finalTime - initialTime;
if(ellapsedTime) {
int fps = frameCount / ellapsedTime;
int sleepMs = (1000 / FPS_LIMIT) - ellapsedTime;
printf("FPS: %i\nMS to Sleep: %i\n", fps, sleepMs);
frameCount = 0;
initialTime = finalTime;
Sleep(sleepMs);
}
}
}
The output I get is: FPS:
FPS: 5749
MS to Sleep: 15
Upvotes: 0
Views: 305
Reputation: 26066
time()
returns the time in integer seconds, which won't work for what you are trying to do.
For instance, at the moment, you only get into the if
once every second or so. sleepMs
is also wrong, since you are subtracting different units.
Upvotes: 1