magmax / python-readchar

Python library to read characters and key strokes
MIT License
143 stars 45 forks source link

Bad while loop pegging CPU on Windows #42

Closed cdgriffith closed 2 years ago

cdgriffith commented 5 years ago

https://github.com/magmax/python-readchar/blob/master/readchar/readchar.py#L71

Nothing slowing this while loop is causing a CPU core to be pegged on Windows. Either removing if msvcrt.kbhit() or adding a time.sleep(0.001) (or similar) is necessary.

leapwill commented 5 years ago

I have a project using readkey() in the main thread while using Selenium WebDriver to launch Firefox in another thread. This issue makes opening Firefox take a few minutes.

I tried both of these ideas, and simply joining the thread (not using readkey() at all), and all options took about 22 seconds with multiple test runs. Both of these suggestions make readkey() effectively transparent in terms of performance.

I don't know enough about msvcrt or best practices of sleep() to know which solution would be better, but I can vouch that both of these suggestions work well.

Cube707 commented 2 years ago

the new v4 under development in #79 should fix this problem, as it relyes on msvcrt.getch() to block untill the next keypress. This seems to be easier on the CPU.

For people needing it the option to run non-blocking is still there, but than the programmer would be responsible for implementing a sleep() to keep CPU usage managable.

Cube707 commented 2 years ago

this should be fixed in v4.0.0 (currently pre-release) as it no longer utilises a loop. can somebody confirm?