具有无限循环的简单脚本会降低计算机速度

时间:2018-12-10 20:02:58

标签: python python-3.x performance infinite-loop win32gui

import win32gui
import pyautogui
import winsound

def get_pixel_colour(i_x, i_y):
    i_desktop_window_id = win32gui.GetDesktopWindow()
    i_desktop_window_dc = win32gui.GetWindowDC(i_desktop_window_id)
    long_colour = win32gui.GetPixel(i_desktop_window_dc, i_x, i_y)
    i_colour = int(long_colour)
    return (i_colour & 0xff), ((i_colour >> 8) & 0xff), ((i_colour >> 16) & 0xff)

def is_top_free(x, y):
    if all(i in range(35,46) for i in get_pixel_colour(x+258, y+108) and get_pixel_colour(x+283, y+108) and get_pixel_colour(x+283, y+139) and get_pixel_colour(x+258, y+139)) and all(i in range(80, 90) for i in get_pixel_colour(x+264, y+131)):
        return True
    else:
        return False

def is_bottom_free(x, y):
    if all(i in range(35, 46) for i in get_pixel_colour(x+256, y+788) and get_pixel_colour(x+286, y+788) and get_pixel_colour(x+256, y+820) and get_pixel_colour(x+286, y+820)) and all(i in range(80, 90) for i in get_pixel_colour(x+264, y+808)):
        return True
    else:
        return False

def get_top_seat(x, y):
    current = pyautogui.position()
    pyautogui.click(x+267, y+126)
    pyautogui.moveTo(current[0], current[1])
    winsound.Beep(500, 500)

def get_bottom_seat(x, y):
    current = pyautogui.position()
    pyautogui.click(x+267, y+802)
    pyautogui.moveTo(current[0], current[1])
    winsound.Beep(500, 500)

def callback(hwnd, extra):
    rect = win32gui.GetWindowRect(hwnd)
    x = rect[0]
    y = rect[1]
    w = rect[2] - x
    h = rect[3] - y
    if win32gui.GetWindowText(hwnd) in accounts:
        if is_top_free(x, y):
            get_top_seat(x, y)
        elif is_bottom_free(x, y):
            get_bottom_seat(x,y)

accounts = ['3948700830', '3949029392', '3949074503', '3949131493', '3949174547', '3949206036']

try:
    while True:
        win32gui.EnumWindows(callback, None)
except KeyboardInterrupt:
    print('End')

此脚本寻找一个按钮,并在可能的情况下单击它。

在运行此脚本时,计算机的运行速度越来越慢。我猜想某些变量将被覆盖而不从内存中删除。我尝试在循环中增加一些睡眠,但是并不能解决问题-速度变慢但仍然很规律。您有什么可能的原因吗?

1 个答案:

答案 0 :(得分:0)

这有助于解决问题:

def get_pixel_colour(i_x, i_y):
    i_desktop_window_id = win32gui.GetDesktopWindow()
    i_desktop_window_dc = win32gui.GetWindowDC(i_desktop_window_id)
    long_colour = win32gui.GetPixel(i_desktop_window_dc, i_x, i_y)
    i_colour = int(long_colour)
    win32gui.ReleaseDC(i_desktop_window_id, i_desktop_window_dc)
    return (i_colour & 0xff), ((i_colour >> 8) & 0xff), ((i_colour >> 16) & 0xff)

谢谢DanMašek!这都是关于实现设备上下文的。