Reputation: 324
I have a programme, which moves the mouse by certain coordinates when held down and it stops it when the mouse key is released. However the code below is taking up 90%+ of my CPU at time. How would I make the code below more efficient / take up less of my CPU's resources?
import pynput
import pyautogui
delta_x = [1,2,3]
delta_y = [3,2,1]
def on_press_start(*args):
if args[-1]:
return False
def on_press_loop(*args):
if not args[-1]:
return False
while True:
i = 0
with Listener(on_click=on_press_start) as listener:
listener.join()
with Listener(on_click=on_press_loop) as listener:
for i in range(len(delta_x)):
pyautogui.move(delta_x[i],delta_y[i])
if not listener.running:
break
print(i)
Upvotes: 1
Views: 382
Reputation: 1015
Even a simple
while True:
pass
loop will use 100% of a CPU core. The efficiency of the code inside the loop will only effect the frequency. It won't effect the CPU usage unless you limit the frequency.
In your case, you don't need a while
loop to monitor the mouse. The listener provided by the library does that for you but in a smarter way. From the docs:
# create a listener
listener = mouse.Listener(on_click=on_click)
...
# start listening to clicks
listener.start()
...
# stop listening to clicks
listener.stop()
When to start/stop listening to mouse events depends on your use case.
Example where the on_click and on_move events are used:
from pynput import mouse
if __name__ == "__main__":
state = {
"left_button_pressed": False
}
def on_click(x, y, button, pressed):
if button == mouse.Button.left:
state["left_button_pressed"] = pressed
print("onclick", x, y, button, pressed)
def on_move(*args):
if state["left_button_pressed"]:
print("on_move", *args)
with mouse.Listener(on_click=on_click, on_move=on_move) as listener:
listener.join()
Upvotes: 1
Reputation: 118
According to https://pynput.readthedocs.io/en/latest/mouse.html,
A mouse listener is a threading.Thread, and all callbacks will be invoked from the thread.
which means that the more Listener you create the more CPU threads it creates, You've a while true loop which will create a ton of listener and a ton of threads due to which your progamme is taking too much CPU.
Upvotes: 2