Skip to content
Advertisement

root.query_pointer()._data causes high CPU usage

I’m a total noob in Python, programming and Linux. I wrote a simple python script to track usage time of various apps. I’ve noticed that after some time python is going nuts utilizing 100% of the CPU. Turns out it’s the code obtaining mouse position is causing issues.

I’ve tried running this code in an empty python script:

import time
from Xlib import display

while True:
    d = display.Display().screen().root.query_pointer()._data
    print(d["root_x"], d["root_y"])
    time.sleep(0.1)

It works but the CPU usage is increasing over time. With time.sleep(1) it takes some time but sooner or later it reaches crazy values.

I’m on Ubuntu 16.04.1 LTS using Python 3.5 with python3-xlib 0.15

Advertisement

Answer

To keep the CPU usual steady I put display.Display().screen() before the loop so that it didn’t have to do so much work all the time. The screen shouldn’t change so nor should that value so it made sense to set it up before.

import time
from Xlib import display
disp = display.Display().screen()
while True:
    d = disp.root.query_pointer()._data
    print(d["root_x"], d["root_y"])
    time.sleep(0.1)

I’ve tested it and it stays at about 0.3% for me.

Hope it this helps 🙂

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement