[1.8] PoC Помощника: трей и замеры на Windows #8
No files matched your search
+57
-35
@@ -1,14 +1,18 @@
|
|||||||
# Замер private working set PoC «Штиль Помощник» (#1.8.1–1.8.2).
|
# Замер памяти PoC «Штиль Помощник» (#1.8.1–1.8.2).
|
||||||
#
|
#
|
||||||
# Запускает release-сборку с флагом --measure-scenario: приложение само
|
# Запускает release-сборку с флагом --measure-scenario: приложение само
|
||||||
# открывает и закрывает окна по таймеру и пишет отметки этапов в
|
# открывает и закрывает окна по таймеру и пишет отметки этапов в
|
||||||
# helper-tray-poc.measure.log рядом с exe. Скрипт снимает private working set
|
# helper-tray-poc.measure.log (рядом с exe, при недоступности — в %TEMP%).
|
||||||
# по отметкам: покой (30 с), открытое окно (+10 с), после закрытия (+10 с),
|
# Скрипт снимает по отметкам два счётчика дерева процессов:
|
||||||
# повторно открытое окно (+10 с). Время открытия берётся из строк
|
# PrivateBytes — committed private memory (решение принимаем по ней:
|
||||||
# «window-opened ... ms=N» в том же логе.
|
# Windows урезает рабочий набор простаивающих процессов,
|
||||||
|
# поэтому WorkingSetPrivate для покоя занижен);
|
||||||
|
# WorkingSetPrivate — private working set, для справки.
|
||||||
|
# Отметки: покой (30 с), открытое окно (+10 с), после закрытия (+10 с),
|
||||||
|
# повторно открытое окно (+10 с). Время открытия — из строк
|
||||||
|
# «window-opened ... ms=N» в логе.
|
||||||
#
|
#
|
||||||
# ОЗУ считается как сумма WorkingSetPrivate по дереву процессов:
|
# Дерево: процесс приложения + все дочерние msedgewebview2.exe (по цепочке
|
||||||
# процесс приложения + все дочерние msedgewebview2.exe (ищем по цепочке
|
|
||||||
# родителей и по user-data-dir в командной строке).
|
# родителей и по user-data-dir в командной строке).
|
||||||
#
|
#
|
||||||
# Использование: powershell -ExecutionPolicy Bypass -File measure.ps1 [-Runs 5]
|
# Использование: powershell -ExecutionPolicy Bypass -File measure.ps1 [-Runs 5]
|
||||||
@@ -22,7 +26,10 @@ param(
|
|||||||
|
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
$WebViewMarker = 'ru.tbsoft.shtil.helper.poc'
|
$WebViewMarker = 'ru.tbsoft.shtil.helper.poc'
|
||||||
$LogPath = Join-Path (Split-Path $ExePath) 'helper-tray-poc.measure.log'
|
$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)) {
|
if (-not (Test-Path $ExePath)) {
|
||||||
throw "Не найден $ExePath — сначала выполните: pnpm tauri build"
|
throw "Не найден $ExePath — сначала выполните: pnpm tauri build"
|
||||||
@@ -33,9 +40,12 @@ function Stop-Poc {
|
|||||||
Get-CimInstance Win32_Process -Filter "Name='msedgewebview2.exe'" |
|
Get-CimInstance Win32_Process -Filter "Name='msedgewebview2.exe'" |
|
||||||
Where-Object { $_.CommandLine -and $_.CommandLine.Contains($WebViewMarker) } |
|
Where-Object { $_.CommandLine -and $_.CommandLine.Contains($WebViewMarker) } |
|
||||||
ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
|
ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
|
||||||
|
# Убитые процессы уходят не мгновенно; если не подождать, следующий прогон
|
||||||
|
# посчитает их за свойства нового (fallback ищет по user-data-dir).
|
||||||
|
Start-Sleep -Seconds 2
|
||||||
}
|
}
|
||||||
|
|
||||||
function Get-TreePrivateWsMb([int]$AppPid) {
|
function Get-TreeMemory([int]$AppPid) {
|
||||||
$all = Get-CimInstance Win32_Process
|
$all = Get-CimInstance Win32_Process
|
||||||
# Дочерние процессы приложения (WebView2 плодит дерево глубиной 2–3 уровня).
|
# Дочерние процессы приложения (WebView2 плодит дерево глубиной 2–3 уровня).
|
||||||
$tree = New-Object 'System.Collections.Generic.List[int]'
|
$tree = New-Object 'System.Collections.Generic.List[int]'
|
||||||
@@ -54,16 +64,18 @@ function Get-TreePrivateWsMb([int]$AppPid) {
|
|||||||
if (-not $tree.Contains($w.ProcessId)) { $tree.Add($w.ProcessId) }
|
if (-not $tree.Contains($w.ProcessId)) { $tree.Add($w.ProcessId) }
|
||||||
}
|
}
|
||||||
$perf = Get-CimInstance Win32_PerfFormattedData_PerfProc_Process
|
$perf = Get-CimInstance Win32_PerfFormattedData_PerfProc_Process
|
||||||
$app = ($perf | Where-Object IDProcess -eq $AppPid | Select-Object -First 1).WorkingSetPrivate
|
$pb = 0.0; $ws = 0.0
|
||||||
$total = 0.0
|
|
||||||
foreach ($tpid in $tree) {
|
foreach ($tpid in $tree) {
|
||||||
$row = $perf | Where-Object IDProcess -eq $tpid | Select-Object -First 1
|
$row = $perf | Where-Object IDProcess -eq $tpid | Select-Object -First 1
|
||||||
if ($row) { $total += $row.WorkingSetPrivate }
|
if ($row) {
|
||||||
|
$pb += $row.PrivateBytes
|
||||||
|
$ws += $row.WorkingSetPrivate
|
||||||
|
}
|
||||||
}
|
}
|
||||||
[pscustomobject]@{
|
[pscustomobject]@{
|
||||||
Pids = $tree.Count
|
Pids = $tree.Count
|
||||||
AppMB = [math]::Round($(if ($app) { $app } else { 0 }) / 1MB, 1)
|
PbMB = [math]::Round($pb / 1MB, 1)
|
||||||
TotalMB = [math]::Round($total / 1MB, 1)
|
WsMB = [math]::Round($ws / 1MB, 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,24 +87,25 @@ function Get-Median([double[]]$Values) {
|
|||||||
$results = @()
|
$results = @()
|
||||||
for ($run = 1; $run -le $Runs; $run++) {
|
for ($run = 1; $run -le $Runs; $run++) {
|
||||||
Stop-Poc
|
Stop-Poc
|
||||||
Remove-Item $LogPath -ErrorAction SilentlyContinue
|
foreach ($log in $LogCandidates) { Remove-Item $log -ErrorAction SilentlyContinue }
|
||||||
Write-Host "── Прогон $run из $Runs ──────────────"
|
Write-Host "── Прогон $run из $Runs ──────────────"
|
||||||
|
|
||||||
$proc = Start-Process $ExePath -ArgumentList '--measure-scenario' -PassThru
|
$proc = Start-Process $ExePath -ArgumentList '--measure-scenario' -PassThru
|
||||||
$seen = 0
|
$seen = 0
|
||||||
$opens = @()
|
$opens = @()
|
||||||
$sample = @{}
|
$sample = @{ Done = $false }
|
||||||
$deadline = (Get-Date).AddSeconds($TimeoutSec)
|
$deadline = (Get-Date).AddSeconds($TimeoutSec)
|
||||||
|
|
||||||
while ((Get-Date) -lt $deadline -and -not $sample.Done) {
|
while ((Get-Date) -lt $deadline -and -not $sample.Done) {
|
||||||
if (Test-Path $LogPath) {
|
$logPath = $LogCandidates | Where-Object { Test-Path $_ } | Select-Object -First 1
|
||||||
foreach ($line in (Get-Content $LogPath | Select-Object -Skip $seen)) {
|
if ($logPath) {
|
||||||
|
foreach ($line in (Get-Content $logPath | Select-Object -Skip $seen)) {
|
||||||
$seen++
|
$seen++
|
||||||
switch -Regex ($line) {
|
switch -Regex ($line) {
|
||||||
'stage open-window-1' { $sample.Idle = Get-TreePrivateWsMb $proc.Id }
|
'stage open-window-1' { $sample.Idle = Get-TreeMemory $proc.Id }
|
||||||
'stage close-window-1' { $sample.Open = Get-TreePrivateWsMb $proc.Id }
|
'stage close-window-1' { $sample.Open = Get-TreeMemory $proc.Id }
|
||||||
'stage open-window-2' { $sample.AfterClose = Get-TreePrivateWsMb $proc.Id }
|
'stage open-window-2' { $sample.AfterClose = Get-TreeMemory $proc.Id }
|
||||||
'stage close-window-2' { $sample.WarmOpen = Get-TreePrivateWsMb $proc.Id }
|
'stage close-window-2' { $sample.WarmOpen = Get-TreeMemory $proc.Id }
|
||||||
'window-opened .*ms=(\d+)' { $opens += [int]$Matches[1] }
|
'window-opened .*ms=(\d+)' { $opens += [int]$Matches[1] }
|
||||||
'stage done' { $sample.Done = $true }
|
'stage done' { $sample.Done = $true }
|
||||||
}
|
}
|
||||||
@@ -101,7 +114,10 @@ for ($run = 1; $run -le $Runs; $run++) {
|
|||||||
Start-Sleep -Milliseconds 200
|
Start-Sleep -Milliseconds 200
|
||||||
}
|
}
|
||||||
|
|
||||||
$proc | Wait-Process -Timeout 15 -ErrorAction SilentlyContinue
|
# После «stage done» приложение должно завершиться само (app.exit(0)
|
||||||
|
# не блокируется prevent_exit — code задан).
|
||||||
|
$null = $proc | Wait-Process -Timeout 10 -ErrorAction SilentlyContinue
|
||||||
|
$selfExited = $proc.HasExited
|
||||||
Stop-Poc
|
Stop-Poc
|
||||||
|
|
||||||
if (-not $sample.Done) {
|
if (-not $sample.Done) {
|
||||||
@@ -110,25 +126,31 @@ for ($run = 1; $run -le $Runs; $run++) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
$results += [pscustomobject]@{
|
$results += [pscustomobject]@{
|
||||||
Run = $run
|
Run = $run
|
||||||
IdleMB = $sample.Idle.TotalMB
|
IdlePbMB = $sample.Idle.PbMB
|
||||||
OpenMB = $sample.Open.TotalMB
|
IdleWsMB = $sample.Idle.WsMB
|
||||||
AfterCloseMB = $sample.AfterClose.TotalMB
|
OpenPbMB = $sample.Open.PbMB
|
||||||
WarmOpenMB = $sample.WarmOpen.TotalMB
|
OpenWsMB = $sample.Open.WsMB
|
||||||
ColdOpenMs = $opens[0]
|
AfterClosePb = $sample.AfterClose.PbMB
|
||||||
WarmOpenMs = $opens[1]
|
AfterCloseWs = $sample.AfterClose.WsMB
|
||||||
|
WarmOpenPb = $sample.WarmOpen.PbMB
|
||||||
|
ColdOpenMs = $opens[0]
|
||||||
|
WarmOpenMs = $opens[1]
|
||||||
|
SelfExit = [bool]$selfExited
|
||||||
}
|
}
|
||||||
Write-Host (" покой {0} МБ · окно {1} МБ · после закрытия {2} МБ · открытие {3}/{4} мс" -f `
|
Write-Host (" покой {0}/{1} МБ · окно {2}/{3} МБ · после закрытия {4}/{5} МБ · открытие {6}/{7} мс" -f `
|
||||||
$sample.Idle.TotalMB, $sample.Open.TotalMB, $sample.AfterClose.TotalMB, $opens[0], $opens[1])
|
$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 "Ни один прогон не завершился" }
|
if (-not $results) { throw "Ни один прогон не завершился" }
|
||||||
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host "══ Итог ($($results.Count) прогонов): медиана [min–max] ══"
|
Write-Host "══ Итог ($($results.Count) прогонов): медиана [min–max], PB = PrivateBytes, WS = WorkingSetPrivate ══"
|
||||||
foreach ($m in 'IdleMB','OpenMB','AfterCloseMB','WarmOpenMB','ColdOpenMs','WarmOpenMs') {
|
foreach ($m in 'IdlePbMB','IdleWsMB','OpenPbMB','OpenWsMB','AfterClosePb','AfterCloseWs','WarmOpenPb','ColdOpenMs','WarmOpenMs') {
|
||||||
$v = @($results | ForEach-Object { [double]$_.$m })
|
$v = @($results | ForEach-Object { [double]$_.$m })
|
||||||
$med = Get-Median $v
|
$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)
|
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
|
$results | Format-Table -AutoSize
|
||||||
@@ -1,9 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "../gen/schemas/desktop-schema.json",
|
"$schema": "../gen/schemas/desktop-schema.json",
|
||||||
"identifier": "helper-windows",
|
"identifier": "helper-windows",
|
||||||
"description": "Окна Помощника, создаваемые динамически из меню трея",
|
"description": "Окна Помощника, создаваемые динамически из меню трея. Команды приложения не входят в ACL, плагинов нет — разрешений не нужно",
|
||||||
"windows": ["win-*"],
|
"windows": ["win-*"],
|
||||||
"permissions": [
|
"permissions": []
|
||||||
"core:default"
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
@@ -143,16 +143,21 @@ fn spawn_measure_scenario(app: AppHandle) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn measure_log_file() -> Option<File> {
|
fn measure_log_file() -> Option<File> {
|
||||||
let dir = std::env::current_exe()
|
let exe_dir = std::env::current_exe()
|
||||||
.ok()
|
|
||||||
.and_then(|p| p.parent().map(|d| d.to_path_buf()))
|
|
||||||
.unwrap_or_else(std::env::temp_dir);
|
|
||||||
OpenOptions::new()
|
|
||||||
.create(true)
|
|
||||||
.write(true)
|
|
||||||
.truncate(true)
|
|
||||||
.open(dir.join("helper-tray-poc.measure.log"))
|
|
||||||
.ok()
|
.ok()
|
||||||
|
.and_then(|p| p.parent().map(|d| d.to_path_buf()));
|
||||||
|
for dir in [exe_dir, Some(std::env::temp_dir())].into_iter().flatten() {
|
||||||
|
match OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.write(true)
|
||||||
|
.truncate(true)
|
||||||
|
.open(dir.join("helper-tray-poc.measure.log"))
|
||||||
|
{
|
||||||
|
Ok(f) => return Some(f),
|
||||||
|
Err(e) => eprintln!("не удалось открыть лог в {}: {}", dir.display(), e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||||
@@ -181,10 +186,13 @@ pub fn run() {
|
|||||||
})
|
})
|
||||||
.build(tauri::generate_context!())
|
.build(tauri::generate_context!())
|
||||||
.expect("error while building tauri application");
|
.expect("error while building tauri application");
|
||||||
// Трею нельзя завершаться при закрытии последнего окна;
|
// Трею нельзя завершаться при закрытии последнего окна (code == None);
|
||||||
// app.exit(0) при этом продолжает работать.
|
// при программном выходе code задан — prevent_exit не вызываем,
|
||||||
|
// иначе app.exit(0) был бы заблокирован.
|
||||||
app.run(|_handle, event| {
|
app.run(|_handle, event| {
|
||||||
if let tauri::RunEvent::ExitRequested { api, .. } = event {
|
if let tauri::RunEvent::ExitRequested { code, api, .. } = event
|
||||||
|
&& code.is_none()
|
||||||
|
{
|
||||||
api.prevent_exit();
|
api.prevent_exit();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
"app": {
|
"app": {
|
||||||
"windows": [],
|
"windows": [],
|
||||||
"security": {
|
"security": {
|
||||||
"csp": "default-src 'self'; style-src 'self' 'unsafe-inline'"
|
"csp": "default-src 'self'; style-src 'self' 'unsafe-inline'; connect-src ipc: http://ipc.localhost"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"bundle": {
|
"bundle": {
|
||||||
|
|||||||
@@ -17,8 +17,11 @@ const description = ref("");
|
|||||||
const sent = ref(false);
|
const sent = ref(false);
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
|
// Двойной rAF: вторая рамка гарантирует, что первая уже отрисована.
|
||||||
requestAnimationFrame(() => {
|
requestAnimationFrame(() => {
|
||||||
void invoke("first_paint");
|
requestAnimationFrame(() => {
|
||||||
|
void invoke("first_paint");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
Reference in new issue
Block a user