I criteri della specifica §9.11 (frame, blocchi del thread, riga aggiornata entro 100 ms, riconnessione sotto i 2 s, nessun ridisegno della griglia con maniglie e finestra) non li misurava nessuno. Ora il simulatore prende --simulatore-aste N (solo con --simulatore): N aste in elenco, tre su quattro in Attiva, ciclo di 5 s e due autopuntate senza fine per asta, così almeno dieci aste stanno sempre sotto i 4 s; senza l'argomento il simulatore resta quello di sempre. tools/Mimante.Schermate ha la modalità --misura <secondi>, tutta via CDP: uno script nella pagina cronometra frame, compiti dell'interfaccia (timer, frame, eventi del puntatore, ResizeObserver) e messaggi del bot, chiude il canale per la riconnessione, trascina la maniglia e ridimensiona la finestra controllando che i <tr data-id> restino gli stessi nodi, che la griglia non scorra né si virtualizzi e che anche lì nessun compito blocchi il thread; scrive misura.json e misura.txt ed esce con 1 se un criterio vincolante fallisce (anche un solo compito lungo del browser) o la misura non vale (basta un campione con meno di dieci aste in finestra critica; la CPU si riporta soltanto). La password può venire da UI_PASSWORD. prove-a-mano.yml ha il lavoro «prestazioni», dopo carico e schermate per non dividere la CPU, e il commento sul mondo del simulatore è corretto. Le prove dei conti della misura stanno in tests/Mimante.Tests con un riferimento a tools/Mimante.Schermate che esiste solo se la cartella c'è: il contesto dell'immagine non ha tools/ e lì quelle prove restano fuori, così la costruzione dell'immagine non si rompe. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
247 lines
12 KiB
C#
247 lines
12 KiB
C#
using System.Diagnostics;
|
||
using System.Text.Json;
|
||
using Mimante.Schermate.Cdp;
|
||
|
||
namespace Mimante.Schermate.Misura;
|
||
|
||
/// <summary>
|
||
/// La misura delle prestazioni (<c>--misura <secondi></c>), tutta via CDP: la pagina Aste del bot avviato con
|
||
/// <c>--simulatore --simulatore-aste 60</c>, già con l'accesso fatto e lo strumento di <see cref="PerfScript"/> dentro.
|
||
///
|
||
/// <para>Fasi: attesa dell'elenco pieno; qualche secondo di assestamento; la misura vera (frame, messaggi, CPU, un
|
||
/// campione al secondo); la maniglia del pannello trascinata avanti e indietro; la finestra ristretta e riallargata;
|
||
/// tre chiusure del canale con il bot. Con maniglia e finestra si guarda che nessuna riga venga ridisegnata e che la
|
||
/// griglia non scorra né si virtualizzi, e i compiti dell'interfaccia si cronometrano come nella misura.</para>
|
||
/// </summary>
|
||
public sealed class PerfRun(CdpClient cdp, string session, Func<string, Task<JsonElement>> eval, Func<int, int, Task> viewport, CancellationToken ct)
|
||
{
|
||
public const int Width = 1600;
|
||
public const int Height = 1000;
|
||
|
||
/// <summary>Quanto aspettare che l'elenco arrivi a <see cref="PerfCriteria.MinListed"/> aste.</summary>
|
||
private static readonly TimeSpan FillTimeout = TimeSpan.FromSeconds(90);
|
||
|
||
private static readonly TimeSpan Settle = TimeSpan.FromSeconds(5);
|
||
|
||
public async Task<PerfInputs> RunAsync(int seconds, Func<IReadOnlyList<string>> errors, Action<string> progress)
|
||
{
|
||
await WaitForListAsync(progress).ConfigureAwait(false);
|
||
await Task.Delay(Settle, ct).ConfigureAwait(false);
|
||
|
||
progress($"misura per {seconds} s");
|
||
var samples = new List<PerfSample>();
|
||
await eval("__mimantePerf.start()").ConfigureAwait(false);
|
||
var cpu0 = await MetricsAsync().ConfigureAwait(false);
|
||
var sw = Stopwatch.StartNew();
|
||
while (sw.Elapsed < TimeSpan.FromSeconds(seconds))
|
||
{
|
||
await Task.Delay(1000, ct).ConfigureAwait(false);
|
||
if (await SampleAsync().ConfigureAwait(false) is { } s) samples.Add(s);
|
||
}
|
||
var cpu1 = await MetricsAsync().ConfigureAwait(false);
|
||
var steady = await eval("__mimantePerf.take()").ConfigureAwait(false);
|
||
|
||
progress("maniglia del pannello");
|
||
var drag = await DragAsync().ConfigureAwait(false);
|
||
progress("ridimensionamento della finestra");
|
||
var resize = await ResizeAsync().ConfigureAwait(false);
|
||
progress("riconnessione");
|
||
var reconnects = new List<double?>();
|
||
for (var i = 0; i < PerfCriteria.ReconnectTrials; i++)
|
||
{
|
||
reconnects.Add(await ReconnectAsync().ConfigureAwait(false));
|
||
await Task.Delay(2000, ct).ConfigureAwait(false);
|
||
}
|
||
|
||
return new PerfInputs
|
||
{
|
||
Seconds = seconds,
|
||
Samples = samples,
|
||
FrameIntervals = Numbers(steady, "frames"),
|
||
RowUpdatesMs = Numbers(steady, "rowUpdates"),
|
||
HandlersMs = Numbers(steady, "handlers"),
|
||
TasksMs = Numbers(steady, "tasks"),
|
||
LongTasksMs = Numbers(steady, "longTasks"),
|
||
CpuPercent = Cpu(cpu0, cpu1),
|
||
Drag = drag,
|
||
Resize = resize,
|
||
ReconnectsMs = reconnects,
|
||
Errors = errors().Distinct().ToList()
|
||
};
|
||
}
|
||
|
||
private async Task WaitForListAsync(Action<string> progress)
|
||
{
|
||
await eval("location.hash = '#/aste'").ConfigureAwait(false);
|
||
var sw = Stopwatch.StartNew();
|
||
var said = false;
|
||
while (sw.Elapsed < FillTimeout)
|
||
{
|
||
var s = await SampleAsync().ConfigureAwait(false);
|
||
if (s is { Listed: >= PerfCriteria.MinListed, Drawn: > 0 }) return;
|
||
if (!said && sw.Elapsed > TimeSpan.FromSeconds(5))
|
||
{
|
||
progress($"aspetto l'elenco: {s?.Listed ?? 0} aste su {PerfCriteria.MinListed}");
|
||
said = true;
|
||
}
|
||
await Task.Delay(1000, ct).ConfigureAwait(false);
|
||
}
|
||
progress("l'elenco non si è riempito: la misura prosegue e risulterà non valida");
|
||
}
|
||
|
||
private async Task<PerfSample?> SampleAsync()
|
||
{
|
||
var v = await eval("__mimantePerf.sample()").ConfigureAwait(false);
|
||
if (v.ValueKind != JsonValueKind.Object) return null;
|
||
return new PerfSample(Int(v, "listed"), Int(v, "active"), Int(v, "critical"), Int(v, "drawn"),
|
||
v.TryGetProperty("connected", out var c) && c.ValueKind == JsonValueKind.True);
|
||
}
|
||
|
||
/// <summary>
|
||
/// La maniglia fra elenco e pannello: premuta, portata a sinistra, a destra e riportata, senza scorrere. Lo
|
||
/// scorrimento e le righe disegnate si guardano prima, dopo ogni tratto e alla fine (<see cref="PerfAnalysis.Grid"/>).
|
||
/// </summary>
|
||
private async Task<GesturePhase> DragAsync()
|
||
{
|
||
var handle = await eval("__mimantePerf.handle()").ConfigureAwait(false);
|
||
if (handle.ValueKind != JsonValueKind.Object)
|
||
return new GesturePhase(new RowIdentity(0, 0, 0, [], []), PerfAnalysis.Frames([]), PerfAnalysis.Tasks([], []), [], 0, PerfAnalysis.Grid([]));
|
||
double x = Double(handle, "x"), y = Double(handle, "y"), panel0 = Double(handle, "panel");
|
||
var grid = new List<(double, int, bool)>();
|
||
var at = 0.0;
|
||
async Task MoveAsync(double target)
|
||
{
|
||
const int steps = 20;
|
||
var from = at;
|
||
for (var i = 1; i <= steps; i++)
|
||
{
|
||
at = from + (target - from) * i / steps;
|
||
await MouseAsync("mouseMoved", x + at, y, 1).ConfigureAwait(false);
|
||
await Task.Delay(16, ct).ConfigureAwait(false);
|
||
}
|
||
}
|
||
|
||
var before = await RowsAsync().ConfigureAwait(false);
|
||
grid.Add(await GridAsync().ConfigureAwait(false));
|
||
await eval("__mimantePerf.start()").ConfigureAwait(false);
|
||
await MouseAsync("mousePressed", x, y, 1).ConfigureAwait(false);
|
||
// Da dove si è a 240 px a sinistra (pannello più largo), poi a 240 px a destra, poi di nuovo al punto di
|
||
// partenza: i limiti del pannello fermano prima, ma lo spostamento fra i due estremi resta.
|
||
double widest = panel0, narrowest = panel0;
|
||
foreach (var target in new[] { -240.0, 240.0, 0.0 })
|
||
{
|
||
await MoveAsync(target).ConfigureAwait(false);
|
||
grid.Add(await GridAsync().ConfigureAwait(false));
|
||
var now = await eval("__mimantePerf.handle()").ConfigureAwait(false);
|
||
if (now.ValueKind != JsonValueKind.Object) continue;
|
||
widest = Math.Max(widest, Double(now, "panel"));
|
||
narrowest = Math.Min(narrowest, Double(now, "panel"));
|
||
}
|
||
await MouseAsync("mouseReleased", x, y, 0).ConfigureAwait(false);
|
||
var moved = widest - narrowest;
|
||
await Task.Delay(300, ct).ConfigureAwait(false);
|
||
var taken = await eval("__mimantePerf.take()").ConfigureAwait(false);
|
||
grid.Add(await GridAsync().ConfigureAwait(false));
|
||
var after = await RowsAsync().ConfigureAwait(false);
|
||
return Phase(before, after, taken, Math.Round(moved, 1), grid);
|
||
}
|
||
|
||
/// <summary>
|
||
/// La finestra da 1600×1000 a 1150×800 (il pannello resta di fianco) e ritorno, a passi di 40 ms; la griglia si
|
||
/// guarda a ogni passo.
|
||
/// </summary>
|
||
private async Task<GesturePhase> ResizeAsync()
|
||
{
|
||
var before = await RowsAsync().ConfigureAwait(false);
|
||
var grid = new List<(double, int, bool)> { await GridAsync().ConfigureAwait(false) };
|
||
await eval("__mimantePerf.start()").ConfigureAwait(false);
|
||
const int steps = 20;
|
||
foreach (var i in Enumerable.Range(1, steps).Concat(Enumerable.Range(0, steps).Reverse()))
|
||
{
|
||
await viewport(Width - 450 * i / steps, Height - 200 * i / steps).ConfigureAwait(false);
|
||
await Task.Delay(40, ct).ConfigureAwait(false);
|
||
grid.Add(await GridAsync().ConfigureAwait(false));
|
||
}
|
||
await viewport(Width, Height).ConfigureAwait(false);
|
||
await Task.Delay(500, ct).ConfigureAwait(false);
|
||
var taken = await eval("__mimantePerf.take()").ConfigureAwait(false);
|
||
grid.Add(await GridAsync().ConfigureAwait(false));
|
||
var after = await RowsAsync().ConfigureAwait(false);
|
||
return Phase(before, after, taken, 0, grid);
|
||
}
|
||
|
||
/// <summary>Una fase dai numeri di <c>__mimantePerf.take()</c>: frame, compiti e compiti lunghi, non solo i frame.</summary>
|
||
private static GesturePhase Phase(IReadOnlyList<(string Id, long Token)> before, IReadOnlyList<(string Id, long Token)> after,
|
||
JsonElement taken, double movedPx, IReadOnlyList<(double, int, bool)> grid) =>
|
||
new(PerfAnalysis.CompareRows(before, after),
|
||
PerfAnalysis.Frames(Numbers(taken, "frames")),
|
||
PerfAnalysis.Tasks(Numbers(taken, "handlers"), Numbers(taken, "tasks")),
|
||
Numbers(taken, "longTasks"),
|
||
movedPx,
|
||
PerfAnalysis.Grid(grid));
|
||
|
||
/// <summary>Scorrimento verticale, righe disegnate e virtualizzazione della griglia in questo momento.</summary>
|
||
private async Task<(double, int, bool)> GridAsync()
|
||
{
|
||
var g = await eval("__mimantePerf.grid()").ConfigureAwait(false);
|
||
if (g.ValueKind != JsonValueKind.Object) return (0, 0, false);
|
||
return (Double(g, "scroll"), Int(g, "drawn"), g.TryGetProperty("virtual", out var v) && v.ValueKind == JsonValueKind.True);
|
||
}
|
||
|
||
/// <summary>Chiude il canale dalla pagina e misura fino al nuovo elenco a schermo; null = non riuscita.</summary>
|
||
private async Task<double?> ReconnectAsync()
|
||
{
|
||
var r = await eval("__mimantePerf.reconnect()").ConfigureAwait(false);
|
||
if (r.ValueKind != JsonValueKind.Object || !r.TryGetProperty("ok", out var ok) || ok.ValueKind != JsonValueKind.True) return null;
|
||
return Double(r, "ms");
|
||
}
|
||
|
||
private async Task<IReadOnlyList<(string Id, long Token)>> RowsAsync()
|
||
{
|
||
var v = await eval("__mimantePerf.rows()").ConfigureAwait(false);
|
||
if (v.ValueKind != JsonValueKind.Array) return [];
|
||
return v.EnumerateArray()
|
||
.Where(p => p.ValueKind == JsonValueKind.Array && p.GetArrayLength() == 2)
|
||
.Select(p => (p[0].ToString(), p[1].TryGetInt64(out var t) ? t : 0L))
|
||
.ToList();
|
||
}
|
||
|
||
private Task MouseAsync(string type, double x, double y, int buttons) =>
|
||
cdp.SendAsync("Input.dispatchMouseEvent", new
|
||
{
|
||
type, x, y, button = type == "mouseMoved" && buttons == 0 ? "none" : "left", buttons, clickCount = type == "mouseMoved" ? 0 : 1
|
||
}, session, ct);
|
||
|
||
/// <summary>TaskDuration e Timestamp di <c>Performance.getMetrics</c>, in secondi.</summary>
|
||
private async Task<(double Task, double Time)?> MetricsAsync()
|
||
{
|
||
try
|
||
{
|
||
var r = await cdp.SendAsync("Performance.getMetrics", sessionId: session, ct: ct).ConfigureAwait(false);
|
||
double? task = null, time = null;
|
||
foreach (var m in r.GetProperty("metrics").EnumerateArray())
|
||
{
|
||
var name = m.GetProperty("name").GetString();
|
||
if (name == "TaskDuration") task = m.GetProperty("value").GetDouble();
|
||
else if (name == "Timestamp") time = m.GetProperty("value").GetDouble();
|
||
}
|
||
return task is { } t && time is { } s ? (t, s) : null;
|
||
}
|
||
catch (CdpException) { return null; }
|
||
}
|
||
|
||
/// <summary>Il tempo del thread della scheda sul tempo trascorso, in percento di un core.</summary>
|
||
public static double? Cpu((double Task, double Time)? start, (double Task, double Time)? end) =>
|
||
start is { } a && end is { } b && b.Time > a.Time ? Math.Round((b.Task - a.Task) / (b.Time - a.Time) * 100, 1) : null;
|
||
|
||
private static IReadOnlyList<double> Numbers(JsonElement obj, string name) =>
|
||
obj.ValueKind == JsonValueKind.Object && obj.TryGetProperty(name, out var a) && a.ValueKind == JsonValueKind.Array
|
||
? a.EnumerateArray().Where(x => x.ValueKind == JsonValueKind.Number).Select(x => x.GetDouble()).ToList()
|
||
: [];
|
||
|
||
private static int Int(JsonElement o, string name) => o.TryGetProperty(name, out var v) && v.TryGetInt32(out var i) ? i : 0;
|
||
|
||
private static double Double(JsonElement o, string name) =>
|
||
o.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number ? v.GetDouble() : 0;
|
||
}
|