Robin Müller
Robin Müller

Reputation: 39

Key press detection triggers high CPU usage

I need to detect a keypress and I am using the keyboard module to do that:

while True:
    try:
        if keyboard.is_pressed('y'):
            pass

Unfortunately, this triggers high CPU usage. Is there a better way?

Upvotes: 0

Views: 178

Answers (1)

Zain Ul Abidin
Zain Ul Abidin

Reputation: 2710

It seems your loop should be blocked for a while to save CPU processing cost try the following approach

import time
while True:
    time.sleep(0.01)
    try:
        if keyboard.is_pressed('y'):
            pass

Also you can use pygame to detect key stokes so that it is even more optimized way, as far as i know pygame does not consume much cpu unless some thing is very promising.

Upvotes: 1

Related Questions