Checking For Keyboard Inputs Uses Too Much Cpu Usage, Is There Something Wrong With My Code?
Im making a simple music player so i can pause music when i am in full screen applications. The code works fine but i noticed that it uses around 15% cpu usage. Im just wondering
Solution 1:
The biggest reason it's consuming so many resources is this:
whileTrue:
In essence, the program never stops to wait for anything. It's checking constantly, over and over, to see if the buttons on the keyboard are pressed. A better way, that's much less costly on the computer, is to assign a "callback" to be called whenever your desired key is pressed, and have the program sleep in between key presses. The keyboard
library provides this functionality:
import keyboard
import time
listedSongs = []
currentSong = "idk"exit = False # make a loop control variable
def alt_k():
i = 1
paused = False
def alt_q():
exit = True
def alt_s():
if currentSong not in listedSongs:
listedSongs.append(currentSong)
print(listedSongs)
# assign hooks to the keyboard
keyboard.on_press_key("alt+k", alt_k) # on press alt+k, execute alt_k()
keyboard.on_press_key("alt+q", alt_q)
keyboard.on_press_key("alt+s", alt_s)
# main loopwhilenotexit:
keyboard.wait() # "block" for input (essentially, do nothing until a key is pressed and yield CPU resources to anything else that wants them)
Post a Comment for "Checking For Keyboard Inputs Uses Too Much Cpu Usage, Is There Something Wrong With My Code?"