Files
shtil/poc/helper-tray/measure.ps1
T

134 lines
6.0 KiB
PowerShell
Raw Normal View History

# Замер private working set PoC «Штиль Помощник» (#1.8.1–1.8.2).
#
# Запускает release-сборку с флагом --measure-scenario: приложение само
# открывает и закрывает окна по таймеру и пишет отметки этапов в
# helper-tray-poc.measure.log рядом с exe. Скрипт снимает private working set
# по отметкам: покой (30 с), открытое окно (+10 с), после закрытия (+10 с),
# повторно открытое окно (+10 с). Время открытия берётся из строк
# «window-opened ... ms=N» в том же логе.
#
# ОЗУ считается как сумма WorkingSetPrivate по дереву процессов:
# процесс приложения + все дочерние msedgewebview2.exe (ищем по цепочке
# родителей и по user-data-dir в командной строке).
#
# Использование: powershell -ExecutionPolicy Bypass -File measure.ps1 [-Runs 5]
# Требуется собранный релиз: pnpm tauri build
param(
[int]$Runs = 5,
[string]$ExePath = "$PSScriptRoot\src-tauri\target\release\helper-tray.exe",
[int]$TimeoutSec = 150
)
$ErrorActionPreference = 'Stop'
$WebViewMarker = 'ru.tbsoft.shtil.helper.poc'
$LogPath = Join-Path (Split-Path $ExePath) 'helper-tray-poc.measure.log'
if (-not (Test-Path $ExePath)) {
throw "Не найден $ExePath — сначала выполните: pnpm tauri build"
}
function Stop-Poc {
Get-Process -Name 'helper-tray' -ErrorAction SilentlyContinue | Stop-Process -Force
Get-CimInstance Win32_Process -Filter "Name='msedgewebview2.exe'" |
Where-Object { $_.CommandLine -and $_.CommandLine.Contains($WebViewMarker) } |
ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
}
function Get-TreePrivateWsMb([int]$AppPid) {
$all = Get-CimInstance Win32_Process
# Дочерние процессы приложения (WebView2 плодит дерево глубиной 2–3 уровня).
$tree = New-Object 'System.Collections.Generic.List[int]'
$tree.Add($AppPid)
for ($i = 0; $i -lt $tree.Count; $i++) {
$parent = $tree[$i]
foreach ($child in ($all | Where-Object ParentProcessId -eq $parent)) {
if (-not $tree.Contains($child.ProcessId)) { $tree.Add($child.ProcessId) }
}
}
# Страховка: webview-процессы, пережившие переодресацию родителя.
foreach ($w in ($all | Where-Object {
$_.Name -eq 'msedgewebview2.exe' -and
$_.CommandLine -and $_.CommandLine.Contains($WebViewMarker)
})) {
if (-not $tree.Contains($w.ProcessId)) { $tree.Add($w.ProcessId) }
}
$perf = Get-CimInstance Win32_PerfFormattedData_PerfProc_Process
$app = ($perf | Where-Object IDProcess -eq $AppPid | Select-Object -First 1).WorkingSetPrivate
$total = 0.0
foreach ($tpid in $tree) {
$row = $perf | Where-Object IDProcess -eq $tpid | Select-Object -First 1
if ($row) { $total += $row.WorkingSetPrivate }
}
[pscustomobject]@{
Pids = $tree.Count
AppMB = [math]::Round($(if ($app) { $app } else { 0 }) / 1MB, 1)
TotalMB = [math]::Round($total / 1MB, 1)
}
}
function Get-Median([double[]]$Values) {
$s = $Values | Sort-Object
return $s[[int]($s.Count / 2)]
}
$results = @()
for ($run = 1; $run -le $Runs; $run++) {
Stop-Poc
Remove-Item $LogPath -ErrorAction SilentlyContinue
Write-Host "── Прогон $run из $Runs ──────────────"
$proc = Start-Process $ExePath -ArgumentList '--measure-scenario' -PassThru
$seen = 0
$opens = @()
$sample = @{}
$deadline = (Get-Date).AddSeconds($TimeoutSec)
while ((Get-Date) -lt $deadline -and -not $sample.Done) {
if (Test-Path $LogPath) {
foreach ($line in (Get-Content $LogPath | Select-Object -Skip $seen)) {
$seen++
switch -Regex ($line) {
'stage open-window-1' { $sample.Idle = Get-TreePrivateWsMb $proc.Id }
'stage close-window-1' { $sample.Open = Get-TreePrivateWsMb $proc.Id }
'stage open-window-2' { $sample.AfterClose = Get-TreePrivateWsMb $proc.Id }
'stage close-window-2' { $sample.WarmOpen = Get-TreePrivateWsMb $proc.Id }
'window-opened .*ms=(\d+)' { $opens += [int]$Matches[1] }
'stage done' { $sample.Done = $true }
}
}
}
Start-Sleep -Milliseconds 200
}
$proc | Wait-Process -Timeout 15 -ErrorAction SilentlyContinue
Stop-Poc
if (-not $sample.Done) {
Write-Warning "Прогон ${run}: сценарий не дошёл до конца за $TimeoutSec с — пропускаю"
continue
}
$results += [pscustomobject]@{
Run = $run
IdleMB = $sample.Idle.TotalMB
OpenMB = $sample.Open.TotalMB
AfterCloseMB = $sample.AfterClose.TotalMB
WarmOpenMB = $sample.WarmOpen.TotalMB
ColdOpenMs = $opens[0]
WarmOpenMs = $opens[1]
}
Write-Host (" покой {0} МБ · окно {1} МБ · после закрытия {2} МБ · открытие {3}/{4} мс" -f `
$sample.Idle.TotalMB, $sample.Open.TotalMB, $sample.AfterClose.TotalMB, $opens[0], $opens[1])
}
if (-not $results) { throw "Ни один прогон не завершился" }
Write-Host ""
Write-Host "══ Итог ($($results.Count) прогонов): медиана [min–max] ══"
foreach ($m in 'IdleMB','OpenMB','AfterCloseMB','WarmOpenMB','ColdOpenMs','WarmOpenMs') {
$v = @($results | ForEach-Object { [double]$_.$m })
$med = Get-Median $v
Write-Host (" {0,-13} {1,8} [{2} – {3}]" -f $m, $med, ($v | Measure-Object -Minimum).Minimum, ($v | Measure-Object -Maximum).Maximum)
}
$results | Format-Table -AutoSize