Reputation: 404
I have a simple program that does the following: 1) User points a mouse somewhere, 2) then user presses Space, 3) and computer does certain amount of left-botton-mouse-clicks at that point.
The program works fine, there is only one problem - it eats 30-50% of processor time on a 4-core processor. Where is the problem?
import pyautogui
import ctypes
pyautogui.FAILSAFE = True
def get_space_state():
hllDll = ctypes.WinDLL ("User32.dll")
VK_SPACE = 0x20
return hllDll.GetKeyState(VK_SPACE)
while True:
if get_space_state() == -127 or get_space_state() == -128:
print ("yes")
pyautogui.click(clicks=40 , interval=0.01)
Thanks a lot.
Upvotes: 1
Views: 136
Reputation: 1272
Correct answer: I suspect a constant polling because of while True:
. Insert sleep or pyautogui.PAUSE there (inside while loop, before if
), if process sleeps for a while (even less then a second) it frees a lot of CPU cycles
Minor optimizations:
Also you're initializing entire User32.dll in every loop... twice (because of or
), it seems.
And User32 is HUGE
Hints and notes:
If I remember python rules right, you just can move hllDll
to a module level (above function defintion), get_space_state()
will find it anyway. Or you can pass it as a parameter. And you don't need to redefine VK_SPACE every function call - though this is a micro-optimization
If all these fixes won't work, you should use debuggers, to find a true source of slowdowns
If you happen to have problems like this in the future, use something like Immunity or WinDbg to attach to process and see what's going on there
Upvotes: 2