首页 > 解决方案 > 检查键盘输入使用过多的 cpu 使用率,我的代码有问题吗?

问题描述

我正在制作一个简单的音乐播放器,因此当我在全屏应用程序中时可以暂停音乐。该代码运行良好,但我注意到它使用了大约 15% 的 cpu 使用率。我只是想知道我的代码是否做错了什么。

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)



任何帮助,将不胜感激 :)

标签: python

解决方案


它消耗这么多资源的最大原因是:

while True:

本质上,程序永远不会停止等待任何东西。它不断地检查,一遍又一遍,看看键盘上的按钮是否被按下。一种更好的方法,这在计算机上的成本要低得多,是分配一个“回调”,以便在您按下所需的键时调用,并让程序在按键之间休眠。该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)

推荐阅读