如何制作一个基本的FPS计数器?

xytpbqjk  于 2022-09-26  发布在  其他
关注(0)|答案(3)|浏览(191)

我正尝试在我的立方体渲染程序中显示每秒的帧数。我想看看它的表演。那么,我该怎么做呢?我已经对此进行了研究,但我看到的示例要么使用了多个类但仍然不起作用,要么使用了我没有的库。有没有办法通过使用像ctime这样的预装库来获得FPS?我正在用C++使用OpenGL。

下面是我的(空)函数:

void GetFPS()
{

}

然后我在渲染函数中使用以下命令显示我的FPS:

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

我的程序设置为60fps,但我希望看到实际的fps,而不是它设置的值。

x33g5p2x

x33g5p2x1#

您必须使用clock()对两个不同的时间间隔进行采样,但请注意其中存在几个问题:

  • 时钟的分辨率为几毫秒(您可以使用std::chrono等解决办法,但根据实现的不同,即使是chrono也可能没有那么高的分辨率。在我的装有GCC 4.9.1的电脑上,我的分辨率从来没有超过16毫秒,即使使用std::chrono也是如此。
  • 最重要的是,使用clock()你会得到很多次0,有时你会测量到实时(在我的情况下,它只有15/16毫秒的跳跃)
  • 除非您使用垂直同步(Vsync),否则您不会测量实际帧时间,而只会测量渲染循环中花费的CPU时间(要激活vsync,您必须通过操作系统函数设置SwapInterval(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的项目中都使用了相同的代码)

dgsult0t

dgsult0t2#

只需节省渲染场景前后的时间,然后进行简单的计算。

下面是一个使用<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;
}
8xiog9wr

8xiog9wr3#

只要在任何循环中调用它,就可以测量每秒的调用次数。


# include <chrono>

void printFPS() {
    static std::chrono::time_point<std::chrono::steady_clock> oldTime = std::chrono::high_resolution_clock::now();
    static int fps; fps++;

    if (std::chrono::duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now() - oldTime) >= std::chrono::seconds{ 1 }) {
        oldTime = std::chrono::high_resolution_clock::now();
        std::cout << "FPS: " << fps <<  std::endl;
        fps = 0;
    }
}

相关问题