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