|
readkey() uses 100% CPU |
Michał Brzozowski
Member #15,090
May 2013
|
Hello, I'm using Allegro 4.2. The readkey() routine uses 100% of the CPU, it seems like it's doing active waiting for a key press. Is there any way to avoid it (different routine?). Maybe I'm doing something wrong? Thanks, |
LennyLen
Member #5,313
December 2004
|
|
Jeff Bernard
Member #6,698
December 2005
|
Michał Brzozowski said: The readkey() routine uses 100% of the CPU Makes sense. readkey() is a blocking function and Allegro 4 doesn't ever natively yield by itself, IIRC. If you don't want to eat the CPU but still block on input, just add a loop checking if there's a key press before calling readkey(): while (!keypressed()) { sleep(0); // yield the CPU however you want. } int keycode = readkey();
-- |
Michał Brzozowski
Member #15,090
May 2013
|
Doesn't make much sense to me, but thanks, it works (I actually had to use usleep(1000), otherwise there was still high CPU usage). |
Arthur Kalliokoski
Second in Command
February 2005
|
The readkey() function apparently asks the OS over and over for a keypress, so naturally it hogs the CPU. Let's say this runs on a 1Ghz cpu. int keycodes[BUFFSIZE]; int i; for(i=0;i<BUFFSIZE;i++) { while (!keypressed()) { //Wild guess, this takes 100 machine cycles usleep(1000); // 1/1000 of a second means 1Ghz rests for 1000000 machine cycles } keycodes[i] = readkey(); //Another wild guess, this takes 1000 cycles } //end of i loop So readkey actually fetches a key 10 times instead of spinning without resting between keys and then getting a key, the keypressed() and usleep "spin", but with a rest in there. They all watch too much MSNBC... they get ideas. |
Michał Brzozowski
Member #15,090
May 2013
|
Thanks, I understand what's going on I just don't understand why readkey() does active waiting, they teach kids in school no to do that |
Arthur Kalliokoski
Second in Command
February 2005
|
When Allegro was first conceived back in the middle of the '90's, just about all programs hogged the CPU, MS-DOS didn't multitask, and those 50Mhz 486's didn't get all that hot. There was a company that made electronically cooled CPU's sometime around there (think of a thermocouple in reverse) and when somebody ran Linux on it, which slept when all the tasks were done, it actually formed frost on it, and when a program warmed the CPU up again, the frost melted and shorted out the motherboard! They all watch too much MSNBC... they get ideas. |
Gideon Weems
Member #3,925
October 2003
|
André Silva
Member #11,991
May 2010
|
Wha? No way! I'm not buying that story! But yeah, without having a cycle that's always asking, and resting for a few milliseconds to not hog the CPU, there's no other way to do it without events, which is why Allegro 5 is so highly recommended.
|
|