FPS管理サンプル for C/C++

FPS(frame per second)を整える方法C/C++によるサンプル


fpser.h

#ifndef _FPSER_
#define _FPSER_

//===================================
//	FPSの調整・管理クラス
//===================================
class Fpser
{
private:
	const static int COUNT=60;

	int Times[COUNT];
	int TimeCount;
	int OldTime;
	double Fps;

	int (*GetTime)();
	void (*Wait)(int);

public:

	Fpser(int (*gettime)(),void (*wait)(int));

	bool Update();
	double GetFps(){ return Fps; }


};


#endif // _FPSER_



fpser.cpp

#include "fpser.h"
//================================================
//	コンストラクタ
//================================================
Fpser::Fpser(int (*gettime)(),void (*wait)(int))
{
	Fps = 0;
	TimeCount=0;
	GetTime=gettime;
	Wait=wait;


	if( GetTime == 0 || Wait == 0 ) return;

	OldTime = GetTime();

}
//================================================
//	時間の更新
//================================================
bool Fpser::Update()
{
	const static double WAIT = 16.6666;

	if( GetTime == 0 || Wait == 0 ) return false;

	//現時間の取得
	int now_time = GetTime()-OldTime;
	int wait_time = (int)((WAIT*(TimeCount+1))+0.5);
	bool time_out = false;

	//タイムアウト
	if( now_time > wait_time ) time_out = true;

	//---------------------------------------
	//	時間調整
	//---------------------------------------
	while( (GetTime()-OldTime) < wait_time ) Wait(0);


	Times[TimeCount] = GetTime()-(OldTime+(int)((WAIT*TimeCount)+0.5));

	//---------------------------------------
	//	FPSの更新
	//---------------------------------------
	if( TimeCount == COUNT-1 )
	{
		int sum = 0;
		for(int i=0;i<COUNT;i++) sum += Times[i];

		double average = double(sum)/double(COUNT);
		if( average != 0 ) Fps = 1000.0/average; else Fps = 0;

		OldTime = GetTime();
	}

	TimeCount = (TimeCount+1)%COUNT;

	return time_out;
}



時間待ち、時間取得が外部依存ですので注意。
Rubyより変動が大きい気がする。