perf: reduce CPU usage whilst idle

When the Maze Solver was idle the wait_for_close() loop ran which
continuously redrew the window in an infinite while loop. This caused
the CPU usage to spike between 70%-80%. This commit removes that method
and uses the _root.mainloop() instead to keep the window visible on the
screen. With this the CPU usage has dropped to > 1% when idle.
This commit is contained in:
Dan Anglin 2024-02-15 01:40:16 +00:00
parent 27cdeaf7f4
commit a919c2698b
Signed by: dananglin
GPG key ID: 0C1D44CFBEE68638
2 changed files with 14 additions and 17 deletions

View file

@ -40,7 +40,6 @@ class Window:
def __init__(self, width: int, height: int) -> None: def __init__(self, width: int, height: int) -> None:
self._root = Tk() self._root = Tk()
self._root.title("Maze Solver") self._root.title("Maze Solver")
self._root.protocol("WM_DELETE_WINDOW", self.close)
# Position the window to the centre of the screen # Position the window to the centre of the screen
screen_width = self._root.winfo_screenwidth() screen_width = self._root.winfo_screenwidth()
@ -61,8 +60,6 @@ class Window:
) )
self._canvas.pack() self._canvas.pack()
self._running = False
def redraw(self) -> None: def redraw(self) -> None:
""" """
redraw redraws all the graphics in the window. redraw redraws all the graphics in the window.
@ -70,23 +67,15 @@ class Window:
self._root.update_idletasks() self._root.update_idletasks()
self._root.update() self._root.update()
def wait_for_close(self) -> None: def mainloop(self) -> None:
""" """
wait_for_close continuously redraws the window until mainloop calls the root widget's mainloop method to
it is set to close. ensure that the window remains visible on the screen.
""" """
self._running = True self._root.mainloop()
while self._running:
self.redraw()
def draw_line(self, line: Line, fill_colour: str = "black") -> None: def draw_line(self, line: Line, fill_colour: str = "black") -> None:
""" """
draw_line draws a line on the canvas. draw_line draws a line on the canvas.
""" """
line.draw(self._canvas, fill_colour) line.draw(self._canvas, fill_colour)
def close(self) -> None:
"""
close sets the window to close.
"""
self._running = False

12
main.py
View file

@ -5,9 +5,17 @@ from maze import Maze
def main(): def main():
window = Window(800, 800) window = Window(800, 800)
_ = Maze(10, 10, 30, 30, 20, 20, window) _ = Maze(
x_position=10,
y_position=10,
num_cell_rows=30,
num_cells_per_row=30,
cell_size_x=20,
cell_size_y=20,
window=window
)
window.wait_for_close() window.mainloop()
if __name__ == "__main__": if __name__ == "__main__":