# Release benchmark helper for budgets 2 to 5 (issue #32, rule #1 in docs/performance.md): the # app's own metrics only (process CPU time, per-thread CPU time and context switches, process GPU # engine time and memory), never system-wide ones. Window lookups happen in C#: PowerShell would # pass $null strings as "". # # Usage, from WSL at the repository root, with the app open (scenarios in docs/performance.md): # powershell.exe -ExecutionPolicy Bypass -File scripts/budget-probe.ps1 info # ... sample -Seconds 30 -Label idle CPU, GPU and memory over one phase; each thread's CPU and wakes # ... trace -Seconds 50 -Label import one line per sample: CPU by kind of thread and priority # ... memory working set, private bytes and GPU memory of the process # ... front | minimize | restore | close (close hides to the notification area) # ... click -X 0.1 -Y 0.07 posted click at fractions of the client area # ... wheel -X 0.5 -Y 0.75 -Delta -120 -Count 150 -Rate 20 # ... cursor -X 0.5 -Y 0.012 puts the real cursor still over the window (the title) # ... shot -Out C:\path\shot.png capture of the window's rectangle on screen # Every phase lasts -Seconds of wall time: keep it under a minute and split longer scenarios. param( [Parameter(Position = 0)][string]$Action = 'info', [double]$Seconds = 30, [string]$Label = '', [double]$X = 0.5, [double]$Y = 0.5, [int]$Delta = -120, [int]$Count = 1, [double]$Rate = 20, [string]$Out = '' ) $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 -ReferencedAssemblies System.Drawing -Language CSharp -TypeDefinition @' using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Runtime.InteropServices; using System.Text; using System.Threading; public static class BudgetProbe { [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; } [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; } [StructLayout(LayoutKind.Sequential)] struct LASTINPUTINFO { public uint cbSize; public uint dwTime; } delegate bool EnumProc(IntPtr h, IntPtr l); [DllImport("user32.dll")] static extern bool EnumWindows(EnumProc cb, IntPtr l); [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid); [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern IntPtr GetPropW(IntPtr h, string name); [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetWindowTextW(IntPtr h, StringBuilder s, int n); [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h); [DllImport("user32.dll")] static extern bool IsIconic(IntPtr h); [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr h, int cmd); [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr h); [DllImport("user32.dll")] static extern bool GetClientRect(IntPtr h, out RECT r); [DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr h, out RECT r); [DllImport("user32.dll")] static extern bool ClientToScreen(IntPtr h, ref POINT p); [DllImport("user32.dll")] static extern bool PostMessageW(IntPtr h, uint m, IntPtr w, IntPtr l); [DllImport("user32.dll")] static extern bool SetCursorPos(int x, int y); [DllImport("user32.dll")] static extern bool GetLastInputInfo(ref LASTINPUTINFO info); [DllImport("user32.dll")] public static extern bool SetProcessDPIAware(); // Seconds since the user last touched the keyboard or mouse: measuring waits while they use // the machine. public static double UserIdleSeconds() { var info = new LASTINPUTINFO(); info.cbSize = 8; GetLastInputInfo(ref info); return (Environment.TickCount - (int)info.dwTime) / 1000.0; } // The app's main window, shown or hidden: the window of an arena-tracker process carrying the // single-instance marker, else the one titled "Arena Tracker". public static IntPtr Find() { var pids = new HashSet(); foreach (var p in Process.GetProcessesByName("arena-tracker")) pids.Add((uint)p.Id); IntPtr marked = IntPtr.Zero, titled = IntPtr.Zero; EnumWindows((h, l) => { uint pid; GetWindowThreadProcessId(h, out pid); if (!pids.Contains(pid)) return true; if (GetPropW(h, "nessar.arena-tracker.main-window") != IntPtr.Zero) { marked = h; return false; } var title = new StringBuilder(256); GetWindowTextW(h, title, 256); if (title.ToString() == "Arena Tracker" && titled == IntPtr.Zero) titled = h; return true; }, IntPtr.Zero); return marked != IntPtr.Zero ? marked : titled; } public static IntPtr Need() { var h = Find(); if (h == IntPtr.Zero) throw new Exception("Erreur : aucune fenêtre Arena Tracker."); return h; } public static uint Pid(IntPtr h) { uint pid; GetWindowThreadProcessId(h, out pid); return pid; } public static uint UiThread(IntPtr h) { uint pid; return GetWindowThreadProcessId(h, out pid); } public static string State(IntPtr h) { RECT r; GetClientRect(h, out r); return String.Format("pid {0}, UI thread {1}, visible {2}, minimised {3}, client {4}x{5}", Pid(h), UiThread(h), IsWindowVisible(h), IsIconic(h), r.Right, r.Bottom); } public static void Show(IntPtr h, int cmd) { ShowWindow(h, cmd); } public static void Front(IntPtr h) { ShowWindow(h, 9 /* SW_RESTORE */); SetForegroundWindow(h); } public static void Close(IntPtr h) { PostMessageW(h, 0x0010 /* WM_CLOSE */, IntPtr.Zero, IntPtr.Zero); } static POINT ClientPoint(IntPtr h, double fx, double fy) { RECT r; GetClientRect(h, out r); var p = new POINT(); p.X = (int)(r.Right * fx); p.Y = (int)(r.Bottom * fy); return p; } static IntPtr LParam(int x, int y) { return new IntPtr((x & 0xffff) | ((y & 0xffff) << 16)); } public static void Click(IntPtr h, double fx, double fy) { var p = ClientPoint(h, fx, fy); PostMessageW(h, 0x0200 /* WM_MOUSEMOVE */, IntPtr.Zero, LParam(p.X, p.Y)); Thread.Sleep(30); PostMessageW(h, 0x0201 /* WM_LBUTTONDOWN */, new IntPtr(1), LParam(p.X, p.Y)); Thread.Sleep(30); PostMessageW(h, 0x0202 /* WM_LBUTTONUP */, IntPtr.Zero, LParam(p.X, p.Y)); } public static void Cursor(IntPtr h, double fx, double fy) { var p = ClientPoint(h, fx, fy); ClientToScreen(h, ref p); SetCursorPos(p.X, p.Y); } // WM_MOUSEWHEEL carries screen coordinates. public static void Wheel(IntPtr h, double fx, double fy, int delta, int count, double rate) { var p = ClientPoint(h, fx, fy); ClientToScreen(h, ref p); for (int i = 0; i < count; i++) { PostMessageW(h, 0x020A, new IntPtr((delta & 0xffff) << 16), LParam(p.X, p.Y)); Thread.Sleep((int)(1000 / rate)); } } public static void Shot(IntPtr h, string path) { RECT r; GetWindowRect(h, out r); using (var bitmap = new Bitmap(r.Right - r.Left, r.Bottom - r.Top)) { using (var g = Graphics.FromImage(bitmap)) g.CopyFromScreen(r.Left, r.Top, 0, 0, bitmap.Size); bitmap.Save(path, System.Drawing.Imaging.ImageFormat.Png); } } } '@ [BudgetProbe]::SetProcessDPIAware() | Out-Null # Raw counters of the process: CPU time, each thread's CPU time (100 ns units), context switches # and priorities, GPU engine running time and memory. function Snapshot($procId) { $p = Get-Process -Id $procId $threads = @{} foreach ($t in Get-CimInstance Win32_PerfRawData_PerfProc_Thread -Filter "IDProcess=$procId") { $threads[[uint32]$t.IDThread] = $t } $gpu = 0 foreach ($e in Get-CimInstance Win32_PerfRawData_GPUPerformanceCounters_GPUEngine -Filter "Name LIKE 'pid_$($procId)_%'") { $gpu += [double]$e.RunningTime } [pscustomobject]@{ At = [Diagnostics.Stopwatch]::GetTimestamp(); Cpu = $p.TotalProcessorTime.TotalMilliseconds Threads = $threads; GpuMs = $gpu / 10000.0; Ws = $p.WorkingSet64; Private = $p.PrivateMemorySize64 Count = $p.Threads.Count } } function Seconds($a, $b) { ($b.At - $a.At) / [Diagnostics.Stopwatch]::Frequency } # A measurement only means something on a known machine and build (docs/performance.md). function Machine($procId) { $cpu = (Get-CimInstance Win32_Processor | Select-Object -First 1).Name.Trim() $game = [bool](Get-Process 'League of Legends' -ErrorAction SilentlyContinue) "Machine: $cpu; user idle for $([Math]::Round([BudgetProbe]::UserIdleSeconds())) s; game running: $game" if ($procId) { "Build: $((Get-Process -Id $procId).Path)" } } function Memory($procId) { $p = Get-Process -Id $procId $g = Get-CimInstance Win32_PerfRawData_GPUPerformanceCounters_GPUProcessMemory -Filter "Name LIKE 'pid_$($procId)_%'" "Memory: working set {0:F1} MB, private {1:F1} MB, peak working set {2:F1} MB; GPU shared {3:F1} MB, dedicated {4:F1} MB, committed {5:F1} MB" -f ` ($p.WorkingSet64 / 1MB), ($p.PrivateMemorySize64 / 1MB), ($p.PeakWorkingSet64 / 1MB), (($g | Measure-Object SharedUsage -Sum).Sum / 1MB), (($g | Measure-Object DedicatedUsage -Sum).Sum / 1MB), (($g | Measure-Object TotalCommitted -Sum).Sum / 1MB) } function AppPid() { $h = [BudgetProbe]::Find() if ($h -ne [IntPtr]::Zero) { return [BudgetProbe]::Pid($h) } $p = Get-Process arena-tracker -ErrorAction SilentlyContinue | Select-Object -First 1 if (-not $p) { throw "Erreur : Arena Tracker n'est pas lancé." } $p.Id } switch ($Action) { 'info' { $procId = AppPid Machine $procId $h = [BudgetProbe]::Find() if ($h -ne [IntPtr]::Zero) { "Window: $([BudgetProbe]::State($h))" } Memory $procId } 'memory' { Memory (AppPid) } 'sample' { $procId = AppPid Machine $procId $h = [BudgetProbe]::Need(); $ui = [BudgetProbe]::UiThread($h) "Window: $([BudgetProbe]::State($h))" $a = Snapshot $procId Start-Sleep -Milliseconds ([int]($Seconds * 1000)) $b = Snapshot $procId $s = Seconds $a $b; $cpu = $b.Cpu - $a.Cpu "[$Label] over {0:F1} s: process CPU {1:F0} ms ({2:F2}% of one core), GPU {3:F1} ms, working set {4:F1} MB, private {5:F1} MB, {6} threads" -f ` $s, $cpu, ($cpu / ($s * 10)), ($b.GpuMs - $a.GpuMs), ($b.Ws / 1MB), ($b.Private / 1MB), $b.Count # Wakes are context switches: a thread waking 60 times a second follows the display. $rows = foreach ($id in $b.Threads.Keys) { $tb = $b.Threads[$id]; $ta = $a.Threads[$id] $cpu0 = 0; $wakes0 = 0 if ($ta) { $cpu0 = [double]$ta.PercentProcessorTime; $wakes0 = [double]$ta.ContextSwitchesPersec } $wakes = [double]$tb.ContextSwitchesPersec - $wakes0 [pscustomobject]@{ Thread = $id; UI = ($id -eq $ui); CpuMs = [Math]::Round(([double]$tb.PercentProcessorTime - $cpu0) / 10000.0, 1) Wakes = $wakes; PerSecond = [Math]::Round($wakes / $s, 1) BasePriority = $tb.PriorityBase; CurrentPriority = $tb.PriorityCurrent; New = (-not $ta) } } $rows | Where-Object { $_.Wakes -gt 0 -or $_.CpuMs -gt 0 } | Sort-Object CpuMs, Wakes -Descending | Format-Table -AutoSize | Out-String -Width 200 "Threads without activity: $(@($rows | Where-Object { $_.Wakes -eq 0 -and $_.CpuMs -eq 0 }).Count)" } 'trace' { # One line per sample, each about 2 to 3 s apart (the counter queries take time): process # CPU, then CPU by kind of thread. ui = the window's thread; vsync = a thread at current # priority 15 waking more than 40 times a second (GPUI's VSyncProvider); low = base # priority below normal; normal = the others. "unseen" is CPU of threads born and gone # between two samples, whose priority is unknown. $procId = AppPid Machine $procId $h = [BudgetProbe]::Find(); $ui = 0 if ($h -ne [IntPtr]::Zero) { $ui = [BudgetProbe]::UiThread($h) } $prev = Snapshot $procId $deadline = $prev.At + [long]($Seconds * [Diagnostics.Stopwatch]::Frequency) $low = 0; $normal = 0; $maxProcess = 0; $maxThread = 0; $normalThreads = @{} while ([Diagnostics.Stopwatch]::GetTimestamp() -lt $deadline) { Start-Sleep -Milliseconds 1000 $cur = Snapshot $procId $s = Seconds $prev $cur $process = ($cur.Cpu - $prev.Cpu) / ($s * 10) $kind = @{ ui = 0.0; vsync = 0.0; low = 0.0; normal = 0.0 }; $top = 0.0; $lowCount = 0 foreach ($id in $cur.Threads.Keys) { $tb = $cur.Threads[$id]; $ta = $prev.Threads[$id] $cpu0 = 0; $wakes0 = 0 if ($ta) { $cpu0 = [double]$ta.PercentProcessorTime; $wakes0 = [double]$ta.ContextSwitchesPersec } $percent = ([double]$tb.PercentProcessorTime - $cpu0) / 100000.0 / $s $wakes = ([double]$tb.ContextSwitchesPersec - $wakes0) / $s if ($percent -gt $top) { $top = $percent } if ($id -eq $ui) { $kind.ui += $percent } elseif ($tb.PriorityCurrent -ge 15 -and $wakes -gt 40) { $kind.vsync += $percent } elseif ([int]$tb.PriorityBase -lt 8) { $kind.low += $percent; if ($percent -gt 0) { $lowCount++ } } else { $kind.normal += $percent if ($percent -gt 0) { $normalThreads[$id] = [Math]::Max([double]$normalThreads[$id], $percent) } } } $unseen = [Math]::Max(0, $process - ($kind.ui + $kind.vsync + $kind.low + $kind.normal)) "process {0,5:F1}% ui {1,4:F1} vsync {2,4:F1} low {3,5:F1} ({4} threads) normal {5,4:F1} unseen {6,4:F1} top thread {7,4:F1}% working set {8:F0} MB" -f ` $process, $kind.ui, $kind.vsync, $kind.low, $lowCount, $kind.normal, $unseen, $top, ($cur.Ws / 1MB) $low += $kind.low * $s / 100; $normal += $kind.normal * $s / 100 if ($process -gt $maxProcess) { $maxProcess = $process } if ($top -gt $maxThread) { $maxThread = $top } $prev = $cur } "[$Label] highest sample: process {0:F1}% of one core, one thread {1:F1}%; background CPU time at low priority {2:F2} s, at normal priority {3:F2} s" -f ` $maxProcess, $maxThread, $low, $normal if ($normalThreads.Count) { "Normal-priority threads with CPU (thread: highest %): " + (($normalThreads.GetEnumerator() | ForEach-Object { "$($_.Key): {0:F1}" -f $_.Value }) -join ', ') } } 'front' { [BudgetProbe]::Front([BudgetProbe]::Need()); [BudgetProbe]::State([BudgetProbe]::Need()) } 'minimize' { [BudgetProbe]::Show([BudgetProbe]::Need(), 6 <# SW_MINIMIZE #>); [BudgetProbe]::State([BudgetProbe]::Need()) } 'restore' { [BudgetProbe]::Show([BudgetProbe]::Need(), 9 <# SW_RESTORE #>); [BudgetProbe]::State([BudgetProbe]::Need()) } 'close' { [BudgetProbe]::Close([BudgetProbe]::Need()); Start-Sleep 1; [BudgetProbe]::State([BudgetProbe]::Need()) } 'click' { [BudgetProbe]::Click([BudgetProbe]::Need(), $X, $Y) } 'cursor' { [BudgetProbe]::Cursor([BudgetProbe]::Need(), $X, $Y) } 'wheel' { [BudgetProbe]::Wheel([BudgetProbe]::Need(), $X, $Y, $Delta, $Count, $Rate) } 'shot' { [BudgetProbe]::Shot([BudgetProbe]::Need(), $Out); "Saved $Out" } default { throw "Erreur : action inconnue '$Action'." } }