Skip to content

Instantly share code, notes, and snippets.

@buddy0452004
Last active March 9, 2026 08:44
Show Gist options
  • Select an option

  • Save buddy0452004/6e40e5f6c70ccd14d1bceee726ffa6ae to your computer and use it in GitHub Desktop.

Select an option

Save buddy0452004/6e40e5f6c70ccd14d1bceee726ffa6ae to your computer and use it in GitHub Desktop.
"""
Matplotlib Overlay Crosshair - Benchmark
Issue #30953 - Approach (b): blit-based overlay
Compares three approaches:
1. Blit-based - cache background, blit only axes region on mouse move
2. Naive - draw_idle() on every mouse move (full redraw)
3. Native (sim) - simulates Qt-native approach timing overhead
Note: True GUI-native (PR #30516) only works with Qt backend.
This script simulates its timing profile for cross-backend comparison.
"""
import time
import numpy as np
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.collections import LineCollection
# ---------------------------------------------------------------------------
# Timing tracker
# ---------------------------------------------------------------------------
class Timer:
def __init__(self, name):
self.name = name
self.times = [] # per-update durations (ms)
self.full_redraws = 0
self.updates = 0
def record(self, duration_ms, full_redraw=False):
self.times.append(duration_ms)
self.updates += 1
if full_redraw:
self.full_redraws += 1
def avg_ms(self):
if not self.times:
return 0.0
return sum(self.times) / len(self.times)
def fps(self):
if not self.times:
return 0.0
avg = self.avg_ms()
return 1000.0 / avg if avg > 0 else 0.0
# ---------------------------------------------------------------------------
# Approach 1: Blit-based crosshair
# ---------------------------------------------------------------------------
class BlitCrosshair:
"""
Caches the figure background after each full draw.
On mouse move: restore background -> draw crosshair -> blit axes region.
Only triggers figure.draw() on zoom/resize (draw_event).
"""
def __init__(self, ax, timer: Timer, color="red", linewidth=1.0):
self.ax = ax
self.canvas = ax.figure.canvas
self.timer = timer
self.color = color
self.lw = linewidth
self._bg = None
self._hline = ax.axhline(y=0, color=color, linewidth=self.lw, visible=False)
self._vline = ax.axvline(x=0, color=color, linewidth=self.lw, visible=False)
self._cid_draw = self.canvas.mpl_connect("draw_event", self._on_draw)
self._cid_move = self.canvas.mpl_connect("motion_notify_event", self._on_move)
self._cid_leave = self.canvas.mpl_connect("axes_leave_event", self._on_leave)
def _on_draw(self, event):
self._bg = self.canvas.copy_from_bbox(self.ax.bbox)
self.timer.record(0, full_redraw=True)
def _on_move(self, event):
if event.inaxes is not self.ax or self._bg is None:
return
t0 = time.perf_counter()
self.canvas.restore_region(self._bg)
self._hline.set_ydata([event.ydata])
self._vline.set_xdata([event.xdata])
self._hline.set_visible(True)
self._vline.set_visible(True)
self.ax.draw_artist(self._hline)
self.ax.draw_artist(self._vline)
self.canvas.blit(self.ax.bbox)
elapsed = (time.perf_counter() - t0) * 1000
self.timer.record(elapsed)
def _on_leave(self, event):
if self._bg is None:
return
self._hline.set_visible(False)
self._vline.set_visible(False)
self.canvas.restore_region(self._bg)
self.canvas.blit(self.ax.bbox)
def disconnect(self):
self.canvas.mpl_disconnect(self._cid_draw)
self.canvas.mpl_disconnect(self._cid_move)
self.canvas.mpl_disconnect(self._cid_leave)
# ---------------------------------------------------------------------------
# Approach 2: Naive crosshair (draw_idle on every move)
# ---------------------------------------------------------------------------
class NaiveCrosshair:
"""
Calls draw_idle() on every mouse move.
Triggers a full figure redraw each time.
Timing measured via draw_event so we capture actual render cost.
"""
def __init__(self, ax, timer: Timer, color="blue", linewidth=1.0):
self.ax = ax
self.canvas = ax.figure.canvas
self.timer = timer
self._t0 = None
self._hline = ax.axhline(y=0, color=color, linewidth=linewidth, visible=False)
self._vline = ax.axvline(x=0, color=color, linewidth=linewidth, visible=False)
self._cid_move = self.canvas.mpl_connect("motion_notify_event", self._on_move)
self._cid_draw = self.canvas.mpl_connect("draw_event", self._on_draw)
self._cid_leave = self.canvas.mpl_connect("axes_leave_event", self._on_leave)
def _on_move(self, event):
if event.inaxes is not self.ax:
return
self._t0 = time.perf_counter()
self._hline.set_ydata([event.ydata])
self._vline.set_xdata([event.xdata])
self._hline.set_visible(True)
self._vline.set_visible(True)
self.canvas.draw_idle()
def _on_draw(self, event):
if self._t0 is not None:
elapsed = (time.perf_counter() - self._t0) * 1000
self.timer.record(elapsed, full_redraw=True)
self._t0 = None
def _on_leave(self, event):
self._hline.set_visible(False)
self._vline.set_visible(False)
self.canvas.draw_idle()
def disconnect(self):
self.canvas.mpl_disconnect(self._cid_move)
self.canvas.mpl_disconnect(self._cid_draw)
self.canvas.mpl_disconnect(self._cid_leave)
# ---------------------------------------------------------------------------
# Approach 3: Native simulation
# ---------------------------------------------------------------------------
class NativeSimCrosshair:
"""
Simulates the timing profile of PR #30516 (Qt-native approach).
The real Qt-native implementation (timhoffm's PR #30516):
- mouseMoveEvent -> self.repaint()
- paintEvent draws lines via QPainter.drawLine() directly on the widget
- Zero matplotlib rendering overhead
Since we cannot run Qt-native outside Qt backend, this simulation:
- Skips all matplotlib rendering
- Only computes the crosshair geometry (same as Qt does)
- Records just the coordinate math overhead
This gives a lower-bound estimate of native timing.
Real native will be close to this — slightly higher due to Qt paint overhead.
"""
def __init__(self, ax, timer: Timer, color="green", linewidth=1.0):
self.ax = ax
self.canvas = ax.figure.canvas
self.timer = timer
self.color = color
# Visual indicator only - not part of timing
self._hline = ax.axhline(y=0, color=color, linewidth=linewidth,
linestyle="--", visible=False, alpha=0.5)
self._vline = ax.axvline(x=0, color=color, linewidth=linewidth,
linestyle="--", visible=False, alpha=0.5)
self._cid_move = self.canvas.mpl_connect("motion_notify_event", self._on_move)
def _on_move(self, event):
if event.inaxes is not self.ax:
return
t0 = time.perf_counter()
# Simulate only the geometry calculation Qt does
# (bbox coords -> line endpoints), no matplotlib rendering
bbox = self.ax.get_position()
fig = self.ax.figure
x0 = int(bbox.x0 * fig.bbox.width)
x1 = int(bbox.x1 * fig.bbox.width)
y0 = int((1 - bbox.y0) * fig.bbox.height)
y1 = int((1 - bbox.y1) * fig.bbox.height)
cx = int(event.x)
cy = int(fig.bbox.height - event.y)
# Simulate: painter.drawLine(x0, cy, x1, cy)
# painter.drawLine(cx, y0, cx, y1)
_ = (x0, cy, x1, cy, cx, y0, cx, y1)
elapsed = (time.perf_counter() - t0) * 1000
self.timer.record(elapsed)
def disconnect(self):
self.canvas.mpl_disconnect(self._cid_move)
# ---------------------------------------------------------------------------
# Live stats overlay
# ---------------------------------------------------------------------------
def attach_stats(fig, timers: dict, interval_ms=500):
"""Update a stats text box every interval_ms."""
txt = fig.text(
0.5, 0.01,
"Move mouse over plots to benchmark...",
ha="center", va="bottom", fontsize=9,
family="monospace",
bbox=dict(boxstyle="round,pad=0.4", facecolor="#f0f0f0", alpha=0.9)
)
def _update(frame):
parts = []
for name, t in timers.items():
if t.updates == 0:
parts.append(f"{name}: waiting...")
else:
parts.append(
f"{name}: avg={t.avg_ms():.3f}ms "
f"fps~{t.fps():.0f} "
f"updates={t.updates} "
f"full_redraws={t.full_redraws}"
)
txt.set_text("\n".join(parts))
fig.canvas.draw_idle()
from matplotlib.animation import FuncAnimation
anim = FuncAnimation(fig, _update, interval=interval_ms, cache_frame_data=False)
return anim
# ---------------------------------------------------------------------------
# Main demo
# ---------------------------------------------------------------------------
def run_benchmark():
lw = 1.0
np.random.seed(42)
x = np.linspace(0, 10, 500)
y = np.sin(x) + 0.1 * np.random.randn(500)
fig, axes = plt.subplots(1, 3, figsize=(18, 5))
fig.suptitle("Crosshair Benchmark: blit vs naive vs native-sim\n"
"Move mouse over each plot quickly", fontsize=12)
titles = [
"[1] Blit (approach b)\ncopy_from_bbox + blit()",
"[2] Naive\ndraw_idle() on every move",
"[3] Native-sim (approach a)\ngeometry only, no mpl render",
]
colors = ["red", "blue", "green"]
for ax, title, color in zip(axes, titles, colors):
ax.plot(x, y, color="steelblue", linewidth=1)
ax.set_title(title, fontsize=9)
ax.set_xlabel("x")
ax.set_ylabel("y")
t_blit = Timer("Blit ")
t_naive = Timer("Naive ")
t_native = Timer("Native-sim")
blit_ch = BlitCrosshair(axes[0], t_blit, color="red", linewidth=lw)
naive_ch = NaiveCrosshair(axes[1], t_naive, color="blue", linewidth=lw)
native_ch = NativeSimCrosshair(axes[2], t_native, color="green", linewidth=lw)
anim = attach_stats(fig, {
"Blit ": t_blit,
"Naive ": t_naive,
"Native-sim": t_native,
})
plt.tight_layout(rect=[0, 0.10, 1, 1])
plt.show()
# Final report
print("\n" + "=" * 60)
print(" BENCHMARK RESULTS")
print("=" * 60)
for name, t in [("Blit", t_blit), ("Naive", t_naive), ("Native-sim", t_native)]:
if t.updates == 0:
print(f" {name}: no data")
continue
print(f"\n {name}:")
print(f" Total updates : {t.updates}")
print(f" Full redraws : {t.full_redraws}")
print(f" Avg per update : {t.avg_ms():.4f} ms")
print(f" Est. max FPS : {t.fps():.1f}")
print("\n Key insight:")
if t_blit.updates > 0 and t_naive.updates > 0:
ratio = t_naive.avg_ms() / max(t_blit.avg_ms(), 0.001)
print(f" Blit is ~{ratio:.1f}x faster than naive per update")
if t_blit.updates > 0 and t_native.updates > 0:
ratio2 = t_blit.avg_ms() / max(t_native.avg_ms(), 0.001)
print(f" Blit overhead vs native-sim: ~{ratio2:.1f}x")
print(f" (native-sim = geometry only, real Qt-native")
print(f" adds Qt paint overhead on top)")
print("=" * 60)
if __name__ == "__main__":
run_benchmark()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment