Files

156 lines
7.5 KiB
PowerShell
Raw Permalink Normal View History

# Замер памяти PoC «Штиль Помощник» (#1.8.1–1.8.2).
#
# Запускает release-сборку с флагом --measure-scenario: приложение само
# открывает и закрывает окна по таймеру и пишет отметки этапов в
# helper-tray-poc.measure.log (рядом с exe, при недоступности — в %TEMP%).
# Скрипт снимает по отметкам два счётчика дерева процессов:
# PrivateBytes — committed private memory (решение принимаем по ней:
# Windows урезает рабочий набор простаивающих процессов,
# поэтому WorkingSetPrivate для покоя занижен);
# WorkingSetPrivate — private working set, для справки.
# Отметки: покой (30 с), открытое окно (+10 с), после закрытия (+10 с),
# повторно открытое окно (+10 с). Время открытия — из строк
# «window-opened ... ms=N» в логе.
#
# Дерево: процесс приложения + все дочерние 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'
$LogCandidates = @(
(Join-Path (Split-Path $ExePath) 'helper-tray-poc.measure.log'),
(Join-Path $env:TEMP '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 }
# Убитые процессы уходят не мгновенно; если не подождать, следующий прогон
# посчитает их за свойства нового (fallback ищет по user-data-dir).
Start-Sleep -Seconds 2
}
function Get-TreeMemory([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
$pb = 0.0; $ws = 0.0
foreach ($tpid in $tree) {
$row = $perf | Where-Object IDProcess -eq $tpid | Select-Object -First 1
if ($row) {
$pb += $row.PrivateBytes
$ws += $row.WorkingSetPrivate
}
}
[pscustomobject]@{
Pids = $tree.Count
PbMB = [math]::Round($pb / 1MB, 1)
WsMB = [math]::Round($ws / 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
foreach ($log in $LogCandidates) { Remove-Item $log -ErrorAction SilentlyContinue }
Write-Host "── Прогон $run из $Runs ──────────────"
$proc = Start-Process $ExePath -ArgumentList '--measure-scenario' -PassThru
$seen = 0
$opens = @()
$sample = @{ Done = $false }
$deadline = (Get-Date).AddSeconds($TimeoutSec)
while ((Get-Date) -lt $deadline -and -not $sample.Done) {
$logPath = $LogCandidates | Where-Object { Test-Path $_ } | Select-Object -First 1
if ($logPath) {
foreach ($line in (Get-Content $logPath | Select-Object -Skip $seen)) {
$seen++
switch -Regex ($line) {
'stage open-window-1' { $sample.Idle = Get-TreeMemory $proc.Id }
'stage close-window-1' { $sample.Open = Get-TreeMemory $proc.Id }
'stage open-window-2' { $sample.AfterClose = Get-TreeMemory $proc.Id }
'stage close-window-2' { $sample.WarmOpen = Get-TreeMemory $proc.Id }
'window-opened .*ms=(\d+)' { $opens += [int]$Matches[1] }
'stage done' { $sample.Done = $true }
}
}
}
Start-Sleep -Milliseconds 200
}
# После «stage done» приложение должно завершиться само (app.exit(0)
# не блокируется prevent_exit — code задан).
$null = $proc | Wait-Process -Timeout 10 -ErrorAction SilentlyContinue
$selfExited = $proc.HasExited
Stop-Poc
if (-not $sample.Done) {
Write-Warning "Прогон ${run}: сценарий не дошёл до конца за $TimeoutSec с — пропускаю"
continue
}
$results += [pscustomobject]@{
Run = $run
IdlePbMB = $sample.Idle.PbMB
IdleWsMB = $sample.Idle.WsMB
OpenPbMB = $sample.Open.PbMB
OpenWsMB = $sample.Open.WsMB
AfterClosePb = $sample.AfterClose.PbMB
AfterCloseWs = $sample.AfterClose.WsMB
WarmOpenPb = $sample.WarmOpen.PbMB
ColdOpenMs = $opens[0]
WarmOpenMs = $opens[1]
SelfExit = [bool]$selfExited
}
Write-Host (" покой {0}/{1} МБ · окно {2}/{3} МБ · после закрытия {4}/{5} МБ · открытие {6}/{7} мс" -f `
$sample.Idle.PbMB, $sample.Idle.WsMB, $sample.Open.PbMB, $sample.Open.WsMB, `
$sample.AfterClose.PbMB, $sample.AfterClose.WsMB, $opens[0], $opens[1])
}
if (-not $results) { throw "Ни один прогон не завершился" }
Write-Host ""
Write-Host "══ Итог ($($results.Count) прогонов): медиана [min–max], PB = PrivateBytes, WS = WorkingSetPrivate ══"
foreach ($m in 'IdlePbMB','IdleWsMB','OpenPbMB','OpenWsMB','AfterClosePb','AfterCloseWs','WarmOpenPb','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)
}
if (-not ($results.SelfExit -contains $false)) { Write-Host " приложение завершилось само во всех прогонах" } else { Write-Warning "были прогоны без самостоятельного завершения" }
$results | Format-Table -AutoSize