【问题标题】:write mouse position to file 100 times a second in python在python中每秒将鼠标位置写入文件100次
【发布时间】:2019-06-25 07:55:00
【问题描述】:

我想每秒将鼠标的位置写入文件 100 次。 但我认为它写得很慢。它在开始时大约每秒写入 80 次,并在一段时间后下降到 5 次。 有没有可能让它更快?

import sys
from datetime import datetime
import time
from Xlib import display

def mousepos():
    data = display.Display().screen().root.query_pointer()._data
    return data["root_x"], data["root_y"]

def get_millis():
    return int(round(time.time() * 1000))

file = open("positions.txt", "a")
data = ''
last_pos = 0,0
start = get_millis()
while True:
    if (get_millis() - start)  >= 10:
        mpos = mousepos()
        if mpos != last_pos:
            data += '{} {}\n'.format(mpos[0], mpos[1])
            last_pos = mpos
        start = get_millis()
        if data != '':
            file.write(data)
            data = ''

【问题讨论】:

  • 将睡眠添加到循环中,这样您就不会一直在循环中使用一个完整的 CPU。 stackoverflow.com/questions/377454/…
  • 你的计时怎么样?您能否包括您所做的以确定它写入文件的速度?

标签: python file-io xlib


【解决方案1】:

您的程序在我的系统上运行良好。可能只是因为让该循环连续运行而使 CPU 过载。尝试在循环末尾添加time.sleep(0.009),让程序休眠 9 毫秒,看看是否有帮助。

更好的是,由于您只需要毫秒级的精度,您可以完全移除对 time.time() 的调用,完全依赖 time.sleep(),如下所示:

import sys
from datetime import datetime
import time
from Xlib import display

def mousepos():
    data = display.Display().screen().root.query_pointer()._data
    return data["root_x"], data["root_y"]

file = open("positions.txt", "a")
last_pos = 0, 0
while True:
    mpos = mousepos()
    if mpos != last_pos:
        data = '{} {}\n'.format(mpos[0], mpos[1])
        file.write(data)
        last_pos = mpos
    time.sleep(0.01)

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多