我想计算游戏最后 2-4 秒的 FPS。最好的方法是什么?
谢谢。
编辑:更具体地说,我只能访问一个以一秒为增量的计时器。
Near miss of a very recent posting. See my response there on using exponential weighted moving averages.
C++: Counting total frames in a game
Here's sample code.
Initially:
avgFps = 1.0; // Initial value should be an estimate, but doesn't matter much.
Every second (assuming the total number of frames in the last second is in framesThisSecond
):
// Choose alpha depending on how fast or slow you want old averages to decay.
// 0.9 is usually a good choice.
avgFps = alpha * avgFps + (1.0 - alpha) * framesThisSecond;
Here's a solution that might work for you. I'll write this in pseudo/C, but you can adapt the idea to your game engine.
const int trackedTime = 3000; // 3 seconds
int frameStartTime; // in milliseconds
int queueAggregate = 0;
queue<int> frameLengths;
void onFrameStart()
{
frameStartTime = getCurrentTime();
}
void onFrameEnd()
{
int frameLength = getCurrentTime() - frameStartTime;
frameLengths.enqueue(frameLength);
queueAggregate += frameLength;
while (queueAggregate > trackedTime)
{
int oldFrame = frameLengths.dequeue();
queueAggregate -= oldFrame;
}
setAverageFps(frameLength.count() / 3); // 3 seconds
}
可以为最后 100 帧保留帧时间的循环缓冲区,并对它们进行平均吗?那将是“最后 100 帧的 FPS”。(或者,更确切地说,99,因为您不会区分最新时间和最旧时间。)
调用一些准确的系统时间,毫秒或更好。
你真正想要的是这样的(在你的 mainLoop 中):
frames++;
if(time<secondsTimer()){
time = secondsTimer();
printf("Average FPS from the last 2 seconds: %d",(frames+lastFrames)/2);
lastFrames = frames;
frames = 0;
}
如果您知道如何处理结构/数组,您应该很容易将此示例扩展到 4 秒而不是 2 秒。但是如果您需要更详细的帮助,您应该真正提及为什么您无法获得精确的计时器(哪种架构,语言) - 否则一切都像猜测......