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

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);
    }
}




你可能感兴趣的:(C语言基础)