質問

I tried to write a CUI Snake game using the ncurses library and C. Everything's working fine, but when I run the program the CPU usage shoots to 50% (from 8ish or lower initially)

After commenting out various parts of the code, I identified the main culprit to be the time delay function I used, which ensures that a new frame is drawn every 90ms. (I obtained the function's source from a website)

void waitFrom(clock_t init, long pauseclocks)
{
    while((clock() - init) < pauseclocks);
}

and in the main function:

clock_t start;
long pause = 90 * (CLOCKS_PER_SEC/1000);
while(1)
{
    start = clock();
    //game code
    waitFrom(start, pause);
}
役に立ちましたか?

解決

The delay would consume 100% of a single core - presumably you have a dual-core processor?

Replace your delay with:

usleep( 90000 ) ;  // 90ms

You need to #include <unistd.h> for usleep().

This will suspend the thread for 90ms rather than busy wait.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top