# -*- coding: utf-8 -*- # 圖 3.4 : Unity 內建輸入 vs Raw Input 的相鄰回報時間間隔直方圖 # 用法 : python plot_input_histogram.py [輸出.jpg] [滑鼠回報率Hz] # 兩個 csv 來自 InputCompareProbe (Test 場景按 F10 存到桌面),欄位 t,dx,dy import sys, os import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib import font_manager for name in ['Microsoft JhengHei', 'Noto Sans CJK TC', 'PingFang TC', 'Microsoft YaHei']: if any(f.name == name for f in font_manager.fontManager.ttflist): plt.rcParams['font.family'] = name; break plt.rcParams['axes.unicode_minus'] = False unity_path, raw_path = sys.argv[1], sys.argv[2] out = sys.argv[3] if len(sys.argv) > 3 else os.path.join(os.path.dirname(os.path.abspath(unity_path)), 'fig3_4_input_histogram.jpg') hz = float(sys.argv[4]) if len(sys.argv) > 4 else None def gaps_ms(path): t = np.loadtxt(path, delimiter=',', skiprows=1, usecols=0, ndmin=1) t = np.sort(t) return np.diff(t) * 1000.0 data = [('Unity Input System(引擎內建)', gaps_ms(unity_path)), ('Windows Raw Input(本研究)', gaps_ms(raw_path))] lo, hi = 1e-3, 50.0 bins = np.logspace(np.log10(lo), np.log10(hi), 80) fig, axes = plt.subplots(1, 2, figsize=(9, 3.6), sharey=True) for ax, (title, g) in zip(axes, data): g = np.clip(g, lo, hi) w = np.full(len(g), 100.0 / len(g)) # 縱軸 : 佔所有相鄰回報的百分比 ax.hist(g, bins=bins, weights=w, color='#4C78A8', edgecolor='white', linewidth=0.3) ax.set_xscale('log'); ax.set_xlim(lo, hi); ax.grid(alpha=0.3, which='both', linewidth=0.5) ax.set_title(title, fontsize=11); ax.set_xlabel('相鄰回報的時間間隔 (ms,對數刻度)') med = np.median(g); near0 = 100.0 * (g < 0.01).mean() ax.axvline(med, color='#333333', linestyle='--', linewidth=1) ax.text(0.98, 0.95, f'事件數 {len(g) + 1:,}\n中位數 {med:.3f} ms\n< 0.01 ms 的比例 {near0:.0f}%', transform=ax.transAxes, ha='right', va='top', fontsize=9, bbox=dict(boxstyle='round,pad=0.4', facecolor='white', edgecolor='#999999', linewidth=0.6)) if hz: ax.axvline(1000.0 / hz, color='#D62728', linestyle=':', linewidth=1) ax.text(1000.0 / hz, ax.get_ylim()[1] if ax.get_ylim()[1] > 0 else 1, f' 1/{hz:.0f} Hz', color='#D62728', fontsize=8, va='top') axes[0].set_ylabel('佔比 (%)') fig.tight_layout(); fig.savefig(out, dpi=200); plt.close(fig) print('已存', out) for title, g in data: print(f'{title} : 事件 {len(g) + 1},中位數 {np.median(g):.3f} ms,< 0.01 ms {100 * (g < 0.01).mean():.1f}%,10%~90% {np.percentile(g, 10):.3f}~{np.percentile(g, 90):.3f} ms')