clicker eats a lot of processor time - python 3

淺唱寂寞╮ 提交于 2019-12-11 06:06:03

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/37373438/clicker-eats-a-lot-of-processor-time-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!