问题
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;
}
}
回答1:
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
}
}
回答2:
frameTime never gets assigned anything other than 0. Presumably that's an error.
回答3:
cout
could be slow so to get more precise value you need to split the time measurement and the output the result.
int main(){
int numFrames = 0;
long totalTime = 0;
while(!done){
// measure time
const Uint32 startTime = SDL_GetTicks();
SDL_Delay( 1.0f/60.0f );
const Uint32 endTime = SDL_GetTicks();
// calculate result
totalTime += endTime - startTime;
++numFrames;
float fps = numFrames / (totalTime / 1000.0);
cout << fps << endl;
}
}
来源:https://stackoverflow.com/questions/5614018/am-i-calculating-my-fps-correctly