Xen*_*nic 7 c++ opengl frame-rate
我正在尝试在我的立方体渲染程序中显示每秒帧数.我想看看它的表现.那么,我该怎么做呢?我已经对此进行了研究,但是我看到的例子使用了多个类但仍然无法工作,或者他们使用的是我没有的库.有没有办法通过使用像ctime这样的预安装库来获取FPS?我正在使用OpenGL和C++.
这是我的(空)函数:
void GetFPS()
{
}
Run Code Online (Sandbox Code Playgroud)
然后我在我的渲染功能中显示我的FPS:
std::cout << xRot << " " << yRot << " " << zRot << " " << FPS << "\n"; //xRot, yRot, and zRot are my cube's rotation.
Run Code Online (Sandbox Code Playgroud)
我的程序设置为60FPS,但我希望看到实际的FPS,而不是它的设置.
Gam*_*per 13
您必须使用2个不同的时间间隔进行采样,clock()
但是请注意存在以下几个问题:
clock()你将获得0次,并且在某个时候你将测量一个实时(在我的情况下它只是跳15/16毫秒)去做:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
当您执行需要几秒钟的操作时,上述代码也适用.我做的计算每秒更新一次,你也可以更频繁地更新它.(注意我在大多数需要FPS的项目中都使用了该代码)
只需在渲染场景之前和之后保存时间"滴答",然后进行简单的计算.
下面是一个使用一个例子<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;
}
Run Code Online (Sandbox Code Playgroud)
只需在任何循环中调用它即可测量每秒的调用次数。
#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;
}
}
Run Code Online (Sandbox Code Playgroud)