1. 程式人生 > >C語言基礎--測試程式中實現對FPS的控制

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