High CPU usage with XNA

后端 未结 2 929
故里飘歌
故里飘歌 2021-02-06 05:42

I just noticed today, that when I compile and run a new XNA 4.0 game, one of CPU threads is running at 100% and the framerate drops to 54 FPS.

The weird thing is that so

2条回答
  •  轮回少年
    2021-02-06 05:57

    High CPU usage (100% on one core) is a non-problem for games. In other words, it's expected. The way you're using the CPU when you write a game demands you do this.

    Open the code environment and write a simple program

    void main(){
        while(1) puts( "aaah" ) ;
    }
    

    Open the CPU monitor and see that 100% of one core is used.

    Now your game is doing this:

    void main(){
        while(1){
            update() ;
            draw() ;
    
            while( getTimeElapsedThisFrame() < 1.0/60.0 ) ; // busy wait, until 16ms have passed
        }
    }
    

    So basically you call update() and draw(), and that takes up most of the 16ms you have to compute a frame (which you will take up most of when your game has a lot of stuff in it).

    Now because O/S sleep resolution is not exact (if you call sleep( 1ms ), it may actually sleep for 20ms before your app wakes up again), what happens is games don't ever call the O/S system function Sleep. The Sleep function would cause your game to "oversleep" as it were and the game would appear laggy and slow.

    Good CPU usage isn't worth having an unresponsive game app. So the standard is to "busy wait" and whittle away the time while hogging the CPU.

提交回复
热议问题