GetCursorPos ctypes与pywin32(win32api / win32gui)使用哪个?

时间:2018-01-06 16:00:10

标签: python winapi win32gui

我找到了在Windows中获取鼠标坐标的三种方法:

from ctypes import windll, Structure, c_long, byref    
class POINT(Structure):
    _fields_ = [("x", c_long), ("y", c_long)]    
def MousePosition_ctypes():
    pos = POINT()
    windll.user32.GetCursorPos(byref(pos))
    return {"x":pos.x,"y":pos.y}

import win32api     
def MousePosition_win32api():
    pos = win32api.GetCursorPos()
    return {"x":pos[0],"y":pos[1]}

import win32gui
def MousePosition_win32gui():
    flags, hcursor, (x,y) = win32gui.GetCursorInfo()
    return {"x":x,"y":y}

他们之间有什么区别?使用ctypes有优势吗? pywin32和ctypes一样吗?

我进行了10 ^ 6次运行的计时测试。

import timeit
print("MousePosition_ctypes  ",timeit.repeat("MousePosition_ctypes()", "from __main__ import MousePosition_windll",number=10**6))
print("MousePosition_win32api",timeit.repeat("MousePosition_win32api()", "from __main__ import MousePosition_win32api",number=10**6))
print("MousePosition_win32gui",timeit.repeat("MousePosition_win32gui()", "from __main__ import MousePosition_win32gui",number=10**6))

结果:

MousePosition_ctypes   [3.171214059203684, 3.0459668639906723, 3.0454502913267243]
MousePosition_win32api [1.9730332863218454, 1.9517156492346004, 2.072004962338813]
MousePosition_win32gui [1.787176519159173, 1.8011713842243182, 1.8127041221688245]

所以win32gui版本将是最快的..

我还测试了每秒获得许多光标坐标的用例。所以我测量了每种方法一分钟内每秒的平均点数:

def store_mouse_track_ctypes(t):
    t0 = time.time()
    list = []
    dt = 0
    while dt < t:
        t1 = time.time()
        position = MousePosition_ctypes()
        t2 = time.time()
        dt = t2 - t0
        list.append([t1,t2,position["x"],position["y"]])
    return list
a = 60
l = store_mouse_track_ctypes(a)
print("store_mouse_track_ctypes",len(l)/a,"points per second.")

结果:

store_mouse_track_ctypes   169850.01666666666 points per second.
store_mouse_track_win32api 225232.46666666667 points per second.
store_mouse_track_win32gui 231186.85 points per second.

再次win32gui版本有点先行。

为什么win32gui版本是“最好的”?

0 个答案:

没有答案