Original Post
Hey all, I am looking for a way to calculate frames per second using just C/C++ time functions. (No GetTickCount!) Thanks!
const float start = static_cast <float> (clock ()) / static_cast <float> (CLOCKS_PER_SEC);while (true) { const float now = (static_cast <float> (clock ()) / static_cast <float> (CLOCKS_PER_SEC)) - start; cout << now << " seconds \r";}float newTime = SomeTimingFunction();float dt = newTime - oldTime;float fps = 1.0f / dt;oldTime = newTime;static const int NUM_FPS_SAMPLES = 64;float fpsSamples[NUM_FPS_SAMPLES]int currentSample = 0;float CalcFPS(int dt){ fpsSamples[currentSample % NUM_FPS_SAMPLES] = 1.0f / dt; float fps = 0; for (int i = 0; i < NUM_FPS_SAMPLES; i++) fps += fpsSamples; fps /= NUM_FPS_SAMPLES; return fps;}
Quote:You'll probably also want to keep the old/new tick values as raw integers until after the subtraction. That way you'll increase the precision and handle timer overflow gracefully.
Original post by MJP float newTime = SomeTimingFunction();float dt = newTime - oldTime;float fps = 1.0f / dt;oldTime = newTime;
Quote:Similarly you could simply store the absolute tick values of each frame in the array here, and subtract the oldest entry from the current tick to get the elapsed time. With increased precision as mentioned above, though that is far less important here, as well as avoiding the loop.
Original post by MJP static const int NUM_FPS_SAMPLES = 64;float fpsSamples[NUM_FPS_SAMPLES]int currentSample = 0;float CalcFPS(int dt){ fpsSamples[currentSample % NUM_FPS_SAMPLES] = 1.0f / dt; float fps = 0; for (int i = 0; i < NUM_FPS_SAMPLES; i++) fps += fpsSamples; fps /= NUM_FPS_SAMPLES; return fps;}
FPS: 75min/avg/max: 0 / 13 / 999Sure it is 75 frames per second. But it is really really bad.FPS: 75min/avg/max: 7 / 13 / 49This is also 75 frames per second, but it reveals useful information about the program.FPS: 75min/avg/max: 13 / 13 / 14Again we're at 75 frames per second, and it is very good.//Inside render loop++frames;overtime = clock() - nextUpdate;if (overtime > 0){ fps = frames / (float)(1+ (float)overtime/(float)CLOCKS_PER_SEC); frames = 0; nextUpdate = clock() + 1 * CLOCKS_PER_SEC;}
This topic has been locked by a moderator. New replies are not allowed.
GameDev.net uses cookies to ensure you have the best experience on our platform. Learn more