Files
grass-cutters/Assets/Scripts/Core/DemoBot.Perf.cs
NiemandKG 80271aea72 Fix Sky Mower tumbling and the hitches on a big farm
- Mowbot keeps its heading apart from the drawn pose: a flyer's lean and sway
  were fed back each frame and rolled it over.
- Drone pads looked through every loose bundle, testing every belt end, for
  each idle drone every frame (43 ms on a 1500-bundle farm): distance first,
  and a 1.5 s pause after finding nothing.
- Saves are written, laid out and compressed off the main thread; backups go
  in the same queue (an autosave froze the game ~50 ms every 30 s).
- Robots tick on staggered frames.
- -demoperf N profiles save slot N; -demobots logs the Sky Mower's tilt.

On the player's save: frames over 25 ms went from 144 to 0 in 40 s, worst
frame 74 ms -> 22 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 19:04:36 +06:00

98 lines
5.2 KiB
C#

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Unity.Profiling;
using Unity.Profiling.LowLevel.Unsafe;
using UnityEngine;
namespace GrassCutter
{
public partial class DemoBot
{
/// <summary>
/// -demoperf N: load save slot N, stand at the base and record where the main thread's time goes for a while:
/// every profiler marker (a development build has one per script Update), the slow frames and what was busy in them.
/// Writes perf.txt beside the shots. Needs a development build for the per-script markers.
/// </summary>
IEnumerator Perf(int slot)
{
SaveSlots.Current = slot - 1;
yield return new WaitForSeconds(2f);
NetSession.Instance.HostLocal();
while (!Me || !Ts) yield return null;
yield return new WaitForSeconds(6f);
var outp = new StringBuilder();
outp.AppendLine($"loaded: {BuildPiece.All.Count} pieces, {Cargo.All.Count} cargo, {Mowbot.All.Count} bots, {Vehicle.All.Count} vehicles, planet r {Planet.Radius:0} m, sectors started {MowMap.Started}, finished {MowMap.Finished}");
int bodies = 0, awake = 0;
foreach (var rb in FindObjectsByType<Rigidbody>(FindObjectsSortMode.None)) { bodies++; if (!rb.isKinematic && !rb.IsSleeping()) awake++; }
outp.AppendLine($"rigidbodies {bodies}, awake {awake}, renderers {FindObjectsByType<Renderer>(FindObjectsSortMode.None).Length}");
var home = Planet.FromBase(0f, -12f);
Me.Teleport(Planet.OnSurface(home) + home * 0.2f);
yield return new WaitForSeconds(1f);
Me.LookAt(Planet.OnSurface(Planet.FromBase(0f, 0f)));
yield return new WaitForSeconds(1f);
// every marker there is, recorded at once
var handles = new List<ProfilerRecorderHandle>();
ProfilerRecorderHandle.GetAvailable(handles);
var recs = new List<(string name, ProfilerRecorder rec)>();
foreach (var h in handles)
{
var d = ProfilerRecorderHandle.GetDescription(h);
if (d.UnitType != ProfilerMarkerDataUnit.TimeNanoseconds) continue;
recs.Add((d.Name, ProfilerRecorder.StartNew(d.Category, d.Name, 1)));
}
var loop = recs.FirstOrDefault(r => r.name == "PlayerLoop").rec;
outp.AppendLine($"recording {recs.Count} markers, PlayerLoop {(loop.Valid ? "ok" : "MISSING")}");
var total = new Dictionary<string, double>();
var spikes = new List<(int frame, double ms, string top)>();
var frames = new List<double>();
float until = Time.realtimeSinceStartup + 40f;
int f = 0;
// walk around a little, as a player would
Ctl.BotMove = new Vector2(0.3f, 1f);
while (Time.realtimeSinceStartup < until)
{
yield return null;
f++;
if (f % 120 == 0) Ctl.BotMove = new Vector2(-Ctl.BotMove.x, Ctl.BotMove.y);
double frameMs = loop.Valid ? loop.LastValue / 1e6 : Time.unscaledDeltaTime * 1000.0;
frames.Add(frameMs);
var busy = new List<(string, double)>();
foreach (var (name, rec) in recs)
{
if (!rec.Valid) continue;
double ms = rec.LastValue / 1e6;
if (ms <= 0 || ms > 1000) continue;
total[name] = (total.TryGetValue(name, out var t) ? t : 0) + ms;
if (frameMs > 25 && ms > 1 && ms < 1000 && (name.StartsWith("GC:") || name.StartsWith("Physics.Simulate") || name.StartsWith("Semaphore") || name.StartsWith("GC.") || name.StartsWith("Gfx."))) busy.Add((name, ms));
}
if (frameMs > 25)
spikes.Add((f, frameMs, string.Join(", ", busy.OrderByDescending(b => b.Item2).Take(10).Select(b => $"{b.Item1} {b.Item2:0.0}"))));
}
Ctl.BotMove = Vector2.zero;
foreach (var (_, rec) in recs) rec.Dispose();
frames.Sort();
double Pct(double p) => frames.Count == 0 ? 0 : frames[Mathf.Clamp((int)(frames.Count * p), 0, frames.Count - 1)];
outp.AppendLine($"{f} frames: mean {frames.Average():0.0} ms, median {Pct(0.5):0.0}, p95 {Pct(0.95):0.0}, p99 {Pct(0.99):0.0}, max {frames.LastOrDefault():0.0}; {spikes.Count} over 25 ms");
outp.AppendLine("— mean ms a frame, top markers —");
foreach (var kv in total.OrderByDescending(kv => kv.Value).Take(70))
outp.AppendLine($"{kv.Value / f,8:0.000} {kv.Key}");
outp.AppendLine("— slow frames —");
foreach (var s in spikes.OrderByDescending(s => s.ms).Take(25))
outp.AppendLine($"#{s.frame} {s.ms:0.0} ms: {s.top}");
float render = 0f;
yield return BotCapture.FrameCost(40, v => render = v);
outp.AppendLine($"render (camera at the base, GPU waited for): {render:0.0} ms");
File.WriteAllText(Path.Combine(folder, "perf.txt"), outp.ToString());
Log("perf done");
Application.Quit();
}
}
}