简体   繁体   English

检查键盘输入使用过多的 CPU 使用率,我的代码有问题吗?

[英]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.代码工作正常,但我注意到它使用了大约 15% 的 CPU 使用率。 Im just wondering if i did something wrong with my code.我只是想知道我的代码是否有问题。

import keyboard

listedSongs = []
currentSong = "idk"
while True:
    if keyboard.is_pressed('alt+k'):
        i = 1
        paused = False
    elif keyboard.is_pressed('alt+q'):
        break
    elif keyboard.is_pressed('alt+s'):
        if currentSong not in listedSongs:
                listedSongs.append(currentSong)
                print(listedSongs)



Any help would be appreciated :)任何帮助,将不胜感激 :)

The biggest reason it's consuming so many resources is this:它消耗这么多资源的最大原因是:

while True:

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: keyboard库提供了这个功能:

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 loop
while not exit:
    keyboard.wait()  # "block" for input (essentially, do nothing until a key is pressed and yield CPU resources to anything else that wants them)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM