您的位置:首页 > 编程语言 > C语言/C++

C语言基础--测试程序中实现对FPS的控制

2017-10-11 21:41 447 查看
const int FRAMES_PER_SECOND = 25;
const int SKIP_TICKS = 1000 / FRAMES_PER_SECOND;

DWORD next_game_tick = GetTickCount();
// GetTickCount() returns the current number of milliseconds
// that have elapsed since the system was started

int sleep_time = 0;

bool game_is_running = true;

while( game_is_running ) {
update_game();
display_game();

next_game_tick += SKIP_TICKS;
sleep_time = next_game_tick - GetTickCount();
if( sleep_time >= 0 ) {
Sleep( sleep_time );
}
else {
// Shit, we are running behind!
}
}


测试程序需要模拟现实中帧的速率(FPS)。

这个问题常出现在game loop中。需要一种方法,在控制FPS的同时,避免CPU的消耗。

问题搜索自 https://stackoverflow.com/questions/771206/how-do-i-cap-my-framerate-at-60-fps-in-java
答案中推荐网站 http://www.koonsolo.com/news/dewitters-gameloop/
以上代码即为引用的代码。

在cocos2d-x游戏框架代码中,也有类似的方法,60fps

long myInterval = 1.0f/60.0f*1000.0f
static long getCurrentMillSecond() {
long lLastTime;
struct timeval stCurrentTime;

gettimeofday(&stCurrentTime,NULL);
lLastTime = stCurrentTime.tv_sec*1000+stCurrentTime.tv_usec*0.001; //millseconds
return lLastTime;
}


while (program_run)
{
lastTime = getCurrentMillSecond();

doSomething();

curTime = getCurrentMillSecond();
if (curTime - lastTime < myInterval)
{
usleep((myInterval - curTime + lastTime)*1000);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐