0

I want to write the position of the mouse to a file 100 times a second. But it writes to slow I think. It writes at the beginning about 80 a second and goes down to 5 after some time. Is it possible to make it faster?

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 = ''
num3ri
  • 822
  • 16
  • 20
  • Add sleep to the loop so that you don't use one full CPU in your loop all the time. https://stackoverflow.com/questions/377454/how-do-i-get-my-python-program-to-sleep-for-50-milliseconds – NineBerry Jan 31 '19 at 19:11
  • How are you doing the timing? Can you include in what you did to determine how fast it's writing to file? – IanQ Jan 31 '19 at 19:12

1 Answers1

2

Your program works fine on my system. It could just be that you are overloading the CPU by having that loop run continuously. Try add in time.sleep(0.009) at the end of the loop to make the program sleep for 9 ms and see if that helps.

Better yet, since you only require accuracy in the order of milliseconds, you can remove the call to time.time() entirely and rely entirely on time.sleep(), like so:

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)