diff --git a/Cargo.lock b/Cargo.lock index bfb698f..aa1f8fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2124,6 +2124,85 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "gpui-fast" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4481f1c7729d23de02a516384278293a4f95a3bdd4b735fc474076675fed9634" +dependencies = [ + "accesskit", + "anyhow", + "async-channel", + "async-task", + "backtrace", + "bitflags 2.13.2", + "chrono", + "derive_more", + "embed-resource", + "etagere", + "futures", + "getrandom 0.3.4", + "gpui-fast-macros", + "gpui-pre-collections", + "gpui-pre-http-client", + "gpui-pre-refineable", + "gpui-pre-scheduler", + "gpui-pre-shared-string", + "gpui-pre-sum-tree", + "gpui-pre-util", + "hdrhistogram", + "heapless", + "icu_segmenter", + "image", + "inventory", + "itertools 0.14.0", + "libc", + "log", + "lyon", + "num_cpus", + "objc2-core-foundation", + "objc2-core-video", + "parking", + "parking_lot", + "pin-project", + "pollster", + "profiling", + "rand 0.9.5", + "raw-window-handle", + "regex", + "resvg 0.46.0", + "schemars", + "seahash", + "serde", + "serde_json", + "slotmap", + "smallvec", + "spin 0.10.1", + "strum", + "taffy", + "thiserror 2.0.21", + "ttf-parser", + "unicode-segmentation", + "url", + "usvg 0.46.0", + "uuid", + "waker-fn", + "windows 0.62.2", + "zed-scap", +] + +[[package]] +name = "gpui-fast-macros" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb3d6ba41781dad8ea9f4b73e0eb122916e31dc9137c5af80eb06a5e750691" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "gpui-kit" version = "0.9.1" @@ -2132,6 +2211,7 @@ checksum = "aca1dedfea73645b60b5893c9c16de0b1396f2cf4251d19e5f03a295c1b61879" dependencies = [ "gpui-base", "gpui-component", + "gpui-fast", "gpui-kit-assets", "gpui-pre", "gpui-pre-macros", @@ -2180,6 +2260,7 @@ dependencies = [ "gpui-pre-shared-string", "gpui-pre-sum-tree", "gpui-pre-util", + "hdrhistogram", "heapless", "icu_segmenter", "image", @@ -2748,6 +2829,16 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "hdrhistogram" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f49d1053f4708f0af3cf9fc5bffc7e68a914a3c45becb231c80068c9c3f78bea" +dependencies = [ + "byteorder", + "num-traits", +] + [[package]] name = "heapless" version = "0.9.3" diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml index ffa6367..c535a8c 100644 --- a/crates/app/Cargo.toml +++ b/crates/app/Cargo.toml @@ -4,6 +4,9 @@ edition.workspace = true rust-version.workspace = true version.workspace = true +[features] +profile = ["gpui-kit/profiler"] + [dependencies] arena-tracker-core = { path = "../core" } gpui-kit = "=0.9.1" diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 55bbd46..69dd7cf 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -1,6 +1,8 @@ #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] mod champion_table; +#[cfg(feature = "profile")] +mod profile; mod settings; mod stats_page; mod text; @@ -177,6 +179,8 @@ fn startup() -> Result> { fn main() { gpui_kit::application().run(move |cx| { gpui_kit::init(cx); + #[cfg(feature = "profile")] + profile::start(cx); let options = WindowOptions { titlebar: Some(TitlebarOptions { title: Some("Arena Tracker".into()), diff --git a/crates/app/src/profile.rs b/crates/app/src/profile.rs new file mode 100644 index 0000000..da255bb --- /dev/null +++ b/crates/app/src/profile.rs @@ -0,0 +1,111 @@ +//! Measurement aid for issue #27, compiled only with `--features profile`. + +use std::fs::{File, OpenOptions}; +use std::io::{self, BufWriter, Write}; +use std::path::Path; +use std::time::Duration; + +use gpui_kit::profiler::journal::{ForegroundEvent, ForegroundJournalEntry}; +use gpui_kit::{App, FrameEvent, FrameTimingCollector, set_trace_enabled}; + +/// Appends issue #27 frame and view measurements when `--features profile` is enabled. +pub fn start(cx: &mut App) { + let Some(path) = std::env::var_os("ARENA_TRACKER_PROFILE") else { + return; + }; + let mut file = match csv_file(Path::new(&path)) { + Ok(file) => file, + Err(error) => { + eprintln!("Could not open profile CSV: {error}"); + return; + } + }; + let mut frames = FrameTimingCollector::new(); + let mut journal = cx.foreground_journal().collector(); + set_trace_enabled(true); + cx.spawn(async move |cx| { + let mut first_event = None; + let mut write_failed = false; + loop { + cx.background_executor().timer(Duration::from_secs(1)).await; + let events = frames.collect_unseen(); + let views: Vec<_> = journal + .collect_unseen() + .entries + .into_iter() + .filter_map(|entry| match entry { + ForegroundJournalEntry::Event(ForegroundEvent::View(timing)) => Some(timing), + _ => None, + }) + .collect(); + let first_at = events + .iter() + .map(|event| match event { + FrameEvent::Draw(timing) => timing.draw_start, + FrameEvent::Present(timing) => timing.present_start, + }) + .chain(views.iter().map(|timing| timing.start)) + .min(); + let Some(first_at) = first_at else { + continue; + }; + let origin = *first_event.get_or_insert(first_at); + let result = (|| { + let mut output = BufWriter::new(&mut file); + for event in events { + match event { + FrameEvent::Draw(timing) => writeln!( + output, + "draw,{:.3},{:.3},{:.3},{:.3},{:.3},{}", + ms(timing.draw_start.duration_since(origin)), + ms(timing.draw_duration()), + ms(timing.phases.request_layout), + ms(timing.phases.prepaint), + ms(timing.phases.paint), + timing.invalidations, + )?, + FrameEvent::Present(timing) => writeln!( + output, + "present,{:.3},{:.3}", + ms(timing.present_start.duration_since(origin)), + ms(timing.present_duration()), + )?, + } + } + for timing in views { + writeln!( + output, + "view,{:.3},\"{}\",{},{:.3}", + ms(timing.start.duration_since(origin)), + timing.name.replace('"', "\"\""), + timing.phase.as_str(), + ms(timing.self_duration), + )?; + } + output.flush() + })(); + if let Err(error) = result + && !write_failed + { + eprintln!("Could not write profile CSV: {error}"); + write_failed = true; + } + } + }) + .detach(); +} + +fn csv_file(path: &Path) -> io::Result { + let mut file = OpenOptions::new().create(true).append(true).open(path)?; + if file.metadata()?.len() == 0 { + writeln!( + file, + "event,elapsed_ms,duration_ms_or_name,request_layout_ms_or_phase,prepaint_ms_or_self_ms,paint_ms,invalidations" + )?; + } + Ok(file) +} + +fn ms(duration: Duration) -> f64 { + duration.as_secs_f64() * 1000. +} diff --git a/crates/app/src/stats_page.rs b/crates/app/src/stats_page.rs index 7bc52b9..58daa93 100644 --- a/crates/app/src/stats_page.rs +++ b/crates/app/src/stats_page.rs @@ -16,6 +16,7 @@ use gpui_kit::component::select::{Select, SelectEvent, SelectItem, SelectState}; use gpui_kit::component::tab::{Tab, TabBar}; use gpui_kit::component::table::{DataTable, TableState}; use gpui_kit::component::{ActiveTheme as _, Disableable as _, IndexPath, Sizable as _}; +use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; use crate::champion_table::ChampionTable; @@ -29,6 +30,32 @@ const CHART_HEIGHT: f32 = 150.; /// While an import runs, the page is recomputed at most this often. const RELOAD_EVERY: Duration = Duration::from_secs(1); +/// Hides page parts for issue #27 measurements only with `--features profile`. +#[inline] +pub fn shown(part: &str) -> bool { + #[cfg(feature = "profile")] + { + static HIDDEN: std::sync::OnceLock> = std::sync::OnceLock::new(); + !HIDDEN + .get_or_init(|| { + std::env::var("ARENA_TRACKER_HIDE") + .unwrap_or_default() + .split(',') + .map(str::trim) + .filter(|part| !part.is_empty()) + .map(str::to_owned) + .collect() + }) + .iter() + .any(|hidden| hidden == part) + } + #[cfg(not(feature = "profile"))] + { + let _ = part; + true + } +} + pub enum PageEvent { OpenSettings, } @@ -645,7 +672,11 @@ impl Render for StatsPage { let mut cards = vec![ card( "Répartition des Placements", - placements_chart(charts), + if shown("placements") { + placements_chart(charts) + } else { + Some(div().size_full().into_any_element()) + }, NO_MATCH, border, muted, @@ -656,7 +687,11 @@ impl Render for StatsPage { cards.push( card( "Champions validés au fil de la Saison", - completed_chart(charts), + if shown("completed") { + completed_chart(charts) + } else { + Some(div().size_full().into_any_element()) + }, "Aucun champion validé", border, muted, @@ -666,7 +701,11 @@ impl Render for StatsPage { cards.push( card( "Tentatives pour valider", - attempts_chart(charts), + if shown("attempts") { + attempts_chart(charts) + } else { + Some(div().size_full().into_any_element()) + }, "Aucun champion validé", border, muted, @@ -682,95 +721,107 @@ impl Render for StatsPage { .size_full() .gap_3() .p_3() - .child( - // The selectors give way first (down to their minimum width), then the buttons - // wrap onto a second line: nothing is ever clipped. - div() - .h_flex() - .flex_wrap() - .items_center() - .justify_between() - .gap_x_3() - .gap_y_2() - .child( - div() - .h_flex() - .items_center() - .gap_3() - .min_w_0() - .child( - Select::new(&self.account_select) - .id("account") - .placeholder("Aucun Compte") - .w(px(260.)) - .min_w(px(150.)), - ) - .children(self.stale().then(|| { - div() - .text_sm() - .whitespace_nowrap() - .text_color(muted) - .child("Non mis à jour") - })) - .child( - Select::new(&self.season_select) - .id("season") - .w(px(220.)) - .min_w(px(130.)), - ) - .child( - Select::new(&self.format_select) - .id("format") - .w(px(220.)) - .min_w(px(130.)), - ), - ) - .child( - div() - .h_flex() - .items_center() - .gap_3() - .flex_shrink_0() - .child( - div() - .text_sm() - .whitespace_nowrap() - .text_color(muted) - .child(status_line), - ) - .child( - Button::new("refresh") - .label("Actualiser") - .disabled(busy) - .on_click(cx.listener(|this, _, _, cx| this.begin_refresh(cx))), - ) - .child(Button::new("settings").label("Paramètres").on_click( - cx.listener(|_, _, _, cx| cx.emit(PageEvent::OpenSettings)), - )), - ), - ) - .child(div().v_flex().gap_1().children(self.banners())) - .children(challenge.map(|c| challenge_tiles(c, self.official(), border, muted))) + .when(shown("header"), |page| { + page.child( + // The selectors give way first (down to their minimum width), then the buttons + // wrap onto a second line: nothing is ever clipped. + div() + .h_flex() + .flex_wrap() + .items_center() + .justify_between() + .gap_x_3() + .gap_y_2() + .child( + div() + .h_flex() + .items_center() + .gap_3() + .min_w_0() + .child( + Select::new(&self.account_select) + .id("account") + .placeholder("Aucun Compte") + .w(px(260.)) + .min_w(px(150.)), + ) + .children(self.stale().then(|| { + div() + .text_sm() + .whitespace_nowrap() + .text_color(muted) + .child("Non mis à jour") + })) + .child( + Select::new(&self.season_select) + .id("season") + .w(px(220.)) + .min_w(px(130.)), + ) + .child( + Select::new(&self.format_select) + .id("format") + .w(px(220.)) + .min_w(px(130.)), + ), + ) + .child( + div() + .h_flex() + .items_center() + .gap_3() + .flex_shrink_0() + .child( + div() + .text_sm() + .whitespace_nowrap() + .text_color(muted) + .child(status_line), + ) + .child( + Button::new("refresh") + .label("Actualiser") + .disabled(busy) + .on_click( + cx.listener(|this, _, _, cx| this.begin_refresh(cx)), + ), + ) + .child(Button::new("settings").label("Paramètres").on_click( + cx.listener(|_, _, _, cx| cx.emit(PageEvent::OpenSettings)), + )), + ), + ) + }) + .when(shown("banners"), |page| { + page.child(div().v_flex().gap_1().children(self.banners())) + }) + .when(shown("tiles"), |page| { + page.children(challenge.map(|c| challenge_tiles(c, self.official(), border, muted))) + }) .child(div().h_flex().gap_3().children(cards)) - .child( - TabBar::new("state-filter") - .segmented() - .selected_index(selected.unwrap_or(0)) - .children(options.iter().map(|(label, _)| Tab::new().label(*label))) - .on_click(cx.listener(|this, ix: &usize, _, cx| { - let in_season = matches!(this.season, SeasonScope::Season(_)); - if let Some((_, filter)) = filters(in_season).get(*ix) { - this.filter = *filter; - this.refresh_table(cx); - cx.notify(); - } - })), - ) - .child( - div() - .flex_1() - .min_h(px(240.)) - .child(DataTable::new(&self.table).stripe(true)), - ) + .when(shown("tabs"), |page| { + page.child( + TabBar::new("state-filter") + .segmented() + .selected_index(selected.unwrap_or(0)) + .children(options.iter().map(|(label, _)| Tab::new().label(*label))) + .on_click(cx.listener(|this, ix: &usize, _, cx| { + let in_season = matches!(this.season, SeasonScope::Season(_)); + if let Some((_, filter)) = filters(in_season).get(*ix) { + this.filter = *filter; + this.refresh_table(cx); + cx.notify(); + } + })), + ) + }) + .when(shown("table"), |page| { + page.child( + div() + .flex_1() + .min_h(px(240.)) + .child(DataTable::new(&self.table).stripe(true)), + ) + }) } } diff --git a/docs/performance.md b/docs/performance.md index 99d916b..f3b43fe 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -34,6 +34,8 @@ A measurement means something only with its machine and build: the probes print Every change that touches rendering, background work or memory measures before and after, with the same scenario, on the reference machine, and records the numbers on its ticket. - **Window moves and idle CPU**: `powershell.exe -ExecutionPolicy Bypass -File scripts/move-probe.ps1 -Title "Arena Tracker"` from WSL, with the app open. It moves the window 240 times per second without touching the mouse, after an idle phase. `MOVE block` is the time each move holds the UI thread, close to the cost of the frame it causes; `IDLE cpu` is budget 2. Compare with File Explorer with `-Class CabinetWClass`. A real title-bar drag (Windows' modal move loop) is not covered: check it by hand. +- **Champion table hover**: `powershell.exe -ExecutionPolicy Bypass -File scripts/hover-probe.ps1 -Title "Arena Tracker"` from WSL, with the statistics page showing the table under the default band (adjust `-Top` and `-Bottom` otherwise). After an idle phase, it posts synthetic mouse moves across table rows 240 times per second without touching the real cursor. Compare `HOVER cpu` with `IDLE cpu`; `HOVER ping` shows how long input waits behind the UI thread while hovering (budget 1). The default band is `-X 0.25 -Top 0.62 -Bottom 0.95 -Step 0.04` (fractions of the client area, about one row per move in a window at least 800 px tall). Leave the real cursor still over the window, outside the table: when it is outside the window, GPUI sees each synthetic move as the mouse entering then leaving, and refreshes the whole window, bypassing cached views. +- **Where a frame goes**: build with `scripts/prod build --features profile` (never for everyday use) and start the app with `ARENA_TRACKER_PROFILE=` (from WSL, pass it through `WSLENV`, e.g. `WSLENV=ARENA_TRACKER_PROFILE/p:ARENA_TRACKER_HIDE`). Every second it appends the frames GPUI drew (`draw`: total, `request_layout`, `prepaint`, `paint` in ms), their presentation (`present`) and the views' own time (`view`, recorded by GPUI from 0.5 ms). `ARENA_TRACKER_HIDE=`, read at start, removes parts of the page so that a part's cost is the difference with the full page under the hover probe: `header`, `banners`, `tiles`, `placements`, `completed`, `attempts` (the three charts keep their height), `tabs`, `table`. - **Memory**: working set of `arena-tracker.exe` in Task Manager, or `Get-Process arena-tracker` in PowerShell, once the page is fully loaded. - **CI cannot check budgets**: its runner is Linux without a GPU, and the app only builds on Windows (ADR-0003). When a change relies on cached views to stay within budget, a structural test (for example, "hovering the table does not render the charts") guards it instead of a timed test. diff --git a/scripts/hover-probe.ps1 b/scripts/hover-probe.ps1 new file mode 100644 index 0000000..ff2d3ac --- /dev/null +++ b/scripts/hover-probe.ps1 @@ -0,0 +1,202 @@ +# Measures the cost of hovering the champion table without touching the mouse (rule #1 +# in docs/performance.md). +# +# After an idle phase, synthetic mouse moves change the hovered row on every move. Their cost +# shows as UI-thread time (CPU and ping latency), not as the time PostMessage takes. Exact +# per-frame times come from a release build with the profile feature and ARENA_TRACKER_PROFILE. +# +# Usage, from WSL at the repository root, with the window open: +# powershell.exe -ExecutionPolicy Bypass -File scripts/hover-probe.ps1 -Title "Arena Tracker" +param( + [string]$Title, + [string]$Class, + [double]$Rate = 240, + [double]$Seconds = 3, + [double]$X = 0.25, + [double]$Top = 0.62, + [double]$Bottom = 0.95, + [double]$Step = 0.04 +) + +$ErrorActionPreference = 'Stop' +# The output is usually read from WSL, which expects UTF-8 (the file itself has a BOM for the +# same reason: Windows PowerShell 5.1 reads scripts without one as ANSI). +[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 + +Add-Type -Language CSharp -TypeDefinition @' +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Threading; + +public static class HoverProbe { + [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; } + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern IntPtr FindWindowW(string cls, string title); + [DllImport("user32.dll")] public static extern bool SetProcessDPIAware(); + [DllImport("user32.dll")] static extern bool GetClientRect(IntPtr h, out RECT r); + [DllImport("user32.dll")] static extern bool PostMessageW(IntPtr h, uint msg, IntPtr w, IntPtr l); + [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid); + [DllImport("user32.dll")] static extern IntPtr SendMessageTimeoutW(IntPtr h, uint msg, IntPtr w, IntPtr l, uint flags, uint timeout, out IntPtr result); + [DllImport("winmm.dll")] static extern uint timeBeginPeriod(uint p); + [DllImport("winmm.dll")] static extern uint timeEndPeriod(uint p); + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + struct MONITORINFOEX { + public int cbSize; public RECT rcMonitor; public RECT rcWork; public uint dwFlags; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string szDevice; + } + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + struct DEVMODE { + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string dmDeviceName; + public short dmSpecVersion, dmDriverVersion, dmSize, dmDriverExtra; public int dmFields; + public int dmPositionX, dmPositionY, dmDisplayOrientation, dmDisplayFixedOutput; + public short dmColor, dmDuplex, dmYResolution, dmTTOption, dmCollate; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string dmFormName; + public short dmLogPixels; public int dmBitsPerPel, dmPelsWidth, dmPelsHeight, dmDisplayFlags, dmDisplayFrequency; + public int dmICMMethod, dmICMIntent, dmMediaType, dmDitherType, dmReserved1, dmReserved2, dmPanningWidth, dmPanningHeight; + } + [DllImport("user32.dll")] static extern IntPtr MonitorFromWindow(IntPtr h, uint flags); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern bool GetMonitorInfoW(IntPtr m, ref MONITORINFOEX info); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern bool EnumDisplaySettingsW(string device, int mode, ref DEVMODE dm); + + const uint SMTO_NORMAL = 0x0; + + // The current mode of the display that shows the window, e.g. "2256x1504 @ 60 Hz". + public static string DisplayOf(IntPtr h) { + var info = new MONITORINFOEX(); info.cbSize = Marshal.SizeOf(typeof(MONITORINFOEX)); + if (!GetMonitorInfoW(MonitorFromWindow(h, 2 /* MONITOR_DEFAULTTONEAREST */), ref info)) return "unknown display"; + var dm = new DEVMODE(); dm.dmSize = (short)Marshal.SizeOf(typeof(DEVMODE)); + if (!EnumDisplaySettingsW(info.szDevice, -1 /* ENUM_CURRENT_SETTINGS */, ref dm)) return info.szDevice; + return String.Format("{0}x{1} @ {2} Hz", dm.dmPelsWidth, dm.dmPelsHeight, dm.dmDisplayFrequency); + } + + public static string ExecutableOf(IntPtr h) { + uint pid; GetWindowThreadProcessId(h, out pid); + try { return Process.GetProcessById((int)pid).MainModule.FileName; } catch (Exception) { return "unknown executable"; } + } + + public static IntPtr Find(string cls, string title) { + return FindWindowW(String.IsNullOrEmpty(cls) ? null : cls, String.IsNullOrEmpty(title) ? null : title); + } + + static double Ms(long ticks) { return ticks * 1000.0 / Stopwatch.Frequency; } + + static string Dist(List xs) { + if (xs.Count == 0) return "n=0"; + xs.Sort(); + Func p = q => xs[Math.Min(xs.Count - 1, (int)(q * xs.Count))]; + return String.Format("n={0} p50={1:F2} p95={2:F2} p99={3:F2} max={4:F2} ms", + xs.Count, p(0.50), p(0.95), p(0.99), xs[xs.Count - 1]); + } + + // Pings the window's thread until stop is set; returns the round-trip latencies in ms. + static List Ping(IntPtr h, Func stop) { + var lat = new List(); + while (!stop()) { + long t0 = Stopwatch.GetTimestamp(); + IntPtr res; + SendMessageTimeoutW(h, 0 /* WM_NULL */, IntPtr.Zero, IntPtr.Zero, SMTO_NORMAL, 2000, out res); + lat.Add(Ms(Stopwatch.GetTimestamp() - t0)); + Thread.Sleep(1); + } + return lat; + } + + static void PostMove(IntPtr h, int x, int y) { + // WM_MOUSEMOVE packs signed client coordinates into the low and high words. + int lparam = (x & 0xffff) | ((y & 0xffff) << 16); + if (!PostMessageW(h, 0x0200 /* WM_MOUSEMOVE */, IntPtr.Zero, new IntPtr(lparam))) + throw new InvalidOperationException("PostMessageW failed."); + } + + public static void Run(IntPtr h, double rate, double seconds, double xFraction, double top, double bottom, double step) { + if (Double.IsNaN(rate) || Double.IsInfinity(rate) || rate <= 0 || rate > Stopwatch.Frequency || + Double.IsNaN(seconds) || Double.IsInfinity(seconds) || seconds <= 0 || + Double.IsNaN(xFraction) || xFraction < 0 || xFraction >= 1 || + Double.IsNaN(top) || Double.IsNaN(bottom) || top < 0 || bottom >= 1 || top >= bottom || + Double.IsNaN(step) || step <= 0 || step > bottom - top) + throw new ArgumentException("Rate and Seconds must be positive; X, Top, Bottom and Step must describe a valid client-area band."); + + RECT r; + if (!GetClientRect(h, out r)) throw new InvalidOperationException("GetClientRect failed."); + int width = r.Right - r.Left, height = r.Bottom - r.Top; + int x = (int)(width * xFraction), yTop = (int)(height * top), yBottom = (int)(height * bottom); + int yStep = (int)Math.Round(height * step); + if (width <= 0 || height <= 0 || width > 32767 || height > 32767 || yStep < 1 || yStep > yBottom - yTop) + throw new ArgumentException("The client area and Step must produce valid physical pixel coordinates."); + + uint pid; + GetWindowThreadProcessId(h, out pid); + var proc = Process.GetProcessById((int)pid); + Console.WriteLine("Target: pid {0} ({1}), rate {2}/s, {3} s per phase, band {4}..{5}, step {6}", pid, proc.ProcessName, rate, seconds, top, bottom, step); + timeBeginPeriod(1); + try { + // Idle phase: nothing happens to the window. + bool stopIdle = false; + List idlePings = null; + var idleThread = new Thread(() => idlePings = Ping(h, () => stopIdle)); + proc.Refresh(); + var cpu0 = proc.TotalProcessorTime; + idleThread.Start(); + Thread.Sleep(TimeSpan.FromSeconds(seconds)); + stopIdle = true; idleThread.Join(); + proc.Refresh(); + var idleCpu = (proc.TotalProcessorTime - cpu0).TotalMilliseconds; + + // Hover phase: sweep by one step per tick, reversing before leaving the band. + bool stopHover = false; + List hoverPings = null; + var hoverThread = new Thread(() => hoverPings = Ping(h, () => stopHover)); + long period = (long)(Stopwatch.Frequency / rate); + long start = Stopwatch.GetTimestamp(), end = start + (long)(seconds * Stopwatch.Frequency); + long next = start; + int moves = 0, dir = 1, y = yTop; + proc.Refresh(); + cpu0 = proc.TotalProcessorTime; + hoverThread.Start(); + double elapsed; + try { + while (Stopwatch.GetTimestamp() < end) { + while (Stopwatch.GetTimestamp() < next) { Thread.SpinWait(50); } + if (y + dir * yStep > yBottom || y + dir * yStep < yTop) dir = -dir; + y += dir * yStep; + PostMove(h, x, y); + moves++; + next += period; + long now = Stopwatch.GetTimestamp(); + if (now > next) next = now; + } + elapsed = Ms(Stopwatch.GetTimestamp() - start) / 1000.0; + } finally { + stopHover = true; hoverThread.Join(); + } + proc.Refresh(); + var hoverCpu = (proc.TotalProcessorTime - cpu0).TotalMilliseconds; + PostMove(h, x, (int)(height * 0.02)); + + Console.WriteLine("IDLE cpu {0:F0} ms over {1} s ({2:F1}% of one core)", idleCpu, seconds, idleCpu / (seconds * 10)); + Console.WriteLine("IDLE ping {0}", Dist(idlePings)); + Console.WriteLine("HOVER achieved {0:F0}/s of {1} requested", moves / elapsed, rate); + Console.WriteLine("HOVER cpu {0:F0} ms over {1:F1} s ({2:F1}% of one core)", hoverCpu, elapsed, hoverCpu / (elapsed * 10)); + Console.WriteLine("HOVER ping {0}", Dist(hoverPings)); + } finally { + timeEndPeriod(1); + } + } +} +'@ + +# Establish physical client coordinates before any window geometry calls. +[void][HoverProbe]::SetProcessDPIAware() +$hwnd = [HoverProbe]::Find($Class, $Title) +if ($hwnd -eq [IntPtr]::Zero) { + Write-Error "Erreur : aucune fenêtre trouvée (classe '$Class', titre '$Title')." +} +# A measurement only means something on a known machine and build (docs/performance.md). +$cpu = (Get-CimInstance Win32_Processor | Select-Object -First 1).Name.Trim() +$gpus = (Get-CimInstance Win32_VideoController | ForEach-Object { $_.Name.Trim() }) -join ', ' +"Machine: $cpu; $gpus; display $([HoverProbe]::DisplayOf($hwnd))" +"Build: $([HoverProbe]::ExecutableOf($hwnd))" +[HoverProbe]::Run($hwnd, $Rate, $Seconds, $X, $Top, $Bottom, $Step)