clicker占用大量处理器时间-python 3 [英] clicker eats a lot of processor time - python 3

查看:100
本文介绍了clicker占用大量处理器时间-python 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的程序,可以执行以下操作:
1)用户将鼠标指向某处,
2)然后用户按空格键,
3),计算机执行一定量的左移操作,

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.

程序运行良好,只有一个问题-它占用4核处理器的30-50%的处理器时间。问题出在哪里?

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) 

非常感谢。

推荐答案

正确答案:我怀疑由于而True:导致持续的轮询。插入 sleep pyautogui.PAUSE 在那里(在while循环内,在 if之前),如果进程休眠一段时间(甚至不到一秒钟),它将释放大量CPU周期

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

次要优化 >:
另外,您似乎在每个循环中都初始化了整个User32.dll ...两次(由于)。
而User32是巨大

提示和笔记

如果我记得正确的python规则,则可以移动 hllDll 到模块级别(在功能定义上方), get_space_state()仍然可以找到它。或者,您可以将其作为参数传递。而且您不需要重新定义每个函数调用的VK_SPACE-尽管这是一个微优化

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

如果将来碰巧遇到此类问题,请使用免疫力 WinDbg 附加到流程并查看发生了什么

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

这篇关于clicker占用大量处理器时间-python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆