How to create a basic FPS counter?

I am trying to display my frames per second in my cube rendering program. I would like to see his work. So how can I do this? I already did research on this, but the examples I saw use either several classes and still do not work, or they use libraries that I don’t have. Is there a way to get FPS using pre-installed libraries like ctime? I am using OpenGL with C ++.

Here is my (empty) function:

void GetFPS()
{

}

and then I show my FPS in my render function with:

std::cout << xRot << " " << yRot << " " << zRot << " " << FPS << "\n"; //xRot, yRot, and zRot are my cube rotation.

My program is installed at 60FPS, but I would like to see the actual FPS, not what it installed.

+4
source share
3

2 , clock() , :

  • ( std:: chrono .., . GCC 4.9.1 , 16 std:: chrono.
  • clock(), 0 , - ( 15/16 ).
  • (vsync), , , ( vsync SetSwapInterval (1), , , SDL, - )
  • , GL ( , , , , , , - ).
  • FPS (, ), , . ( , 100 80 FPS - 2,5 , 40 20 FPS - 25 !)

:

double clockToMilliseconds(clock_t ticks){
    // units/(units/time) => time (seconds) * 1000 = milliseconds
    return (ticks/(double)CLOCKS_PER_SEC)*1000.0;
}
//...

clock_t deltaTime = 0;
unsigned int frames = 0;
double  frameRate = 30;
double  averageFrameTimeMilliseconds = 33.333;

while(rendering){

    clock_t beginFrame = clock();
    render();
    clock_t endFrame = clock();

    deltaTime += endFrame - beginFrame;
    frames ++;

    //if you really want FPS
    if( clockToMilliseconds(deltaTime)>1000.0){ //every second
        frameRate = (double)frames*0.5 +  frameRate*0.5; //more stable
        frames = 0;
        deltaTime -= CLOCKS_PER_SEC;
        averageFrameTimeMilliseconds  = 1000.0/(frameRate==0?0.001:frameRate);

        if(vsync)
            std::cout<<"FrameTime was:"<<averageFrameTimeMilliseconds<<std::endl;
        else
           std::cout<<"CPU time was:"<<averageFrameTimeMilliseconds<<std::endl;
    }
}

, -, . , , . ( , , FPS)

+7

"" , .

, <ctime> clock(). ( , clock() - )

clock_t current_ticks, delta_ticks;
clock_t fps = 0;
while(true)// your main loop. could also be the idle() function in glut or whatever
{
    current_ticks = clock();

    render();

    delta_ticks = clock() - current_ticks; //the time, in ms, that took to render the scene
    if(delta_ticks > 0)
        fps = CLOCKS_PER_SEC / delta_ticks;
    cout << fps << endl;
}
+5

DarioOO code has an error if split as (ticks/(double)CLOCKS_PER_SEC)/1000.0 you don't get milliseconds. so it if( clockToMilliseconds(deltaTime)>1000.0)will never be true, unless it is worth a few minutes

+1
source

All Articles