Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

100% cpu use #4

Closed
amiguet opened this issue Sep 28, 2023 · 4 comments
Closed

100% cpu use #4

amiguet opened this issue Sep 28, 2023 · 4 comments

Comments

@amiguet
Copy link

amiguet commented Sep 28, 2023

Hello,

This is a followup to a beaupy issue.

I noticed that get_key() uses 100% of my cpu. To reproduce, use the code provided in the README:

from yakh import get_key
from yakh.key import Keys

key = ''
while key not in ['q', Keys.ENTER]:
    key = get_key()
    if key.is_printable:
        print(key)

Python 3.11.5 on Linux, python-yakh==0.3.1 installed in a venv via pip as a dependency for beaupy.

@amiguet
Copy link
Author

amiguet commented Sep 28, 2023

No idea if this is the right way of fixing this, but adding a tiny time.sleep in the outer loop of __get_key() in _yakh.py makes the cpu use drop to less than 1%:

            while True:
                if ch_str != "":
                    break
                while True:
                    ch_stri = sys.stdin.read(1)
                    if ch_stri == "":
                        break
                    ch_str += ch_stri
                sleep(.02)

Just my 2¢...

@petereon
Copy link
Owner

@amiguet thank you very much for looking into this.

I will investigate a little bit, as I'd like to avoid an explicit sleep because I am afraid it will mess with stdin stream, which I've found to be exceptionally brittle.

If no better option offers itself, I am going to go for this. If you are so inclined, feel free to open a pull request containing this change.

@amiguet
Copy link
Author

amiguet commented Sep 29, 2023

Wow that was quick!

I didn't know about select.select(), but this is of course a much better solution than the sleep() workaround.

This works very well for me, many thanks! :-)

@petereon
Copy link
Owner

I only learned about it yesterday too. Curiously it popped out as a first result, despite the fact I've spent several hours researching how stdin can be interrogated to see if it has any contents when I was first implementing that.

Glad to be of help!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants