Files
grass-cutters/Assets/Scripts/Core/DemoBot.Perf.cs
NiemandKG 57d0f4d31a Frame time on a big farm: batched grass, sleeping bundles, no light probes
Measured in a real 2560x1440 window on the player's Mommy save (RTX 4090):
the GPU took ~5 ms, the main thread the rest.

- Grass: a fully mown sector draws only its floor (one draw, not up to six);
  untouched and fully mown sectors share a mow map look, so the fur pile
  draws them all in one instanced call per pile (GC_SECTOR_BUFFER, sector
  frames from a structured buffer). Grass draws 1112 -> 337 at the base,
  876 -> 439 in the meadow.
- Bundles: loose ones sleep when they come to rest (our gravity kept ~600
  bodies awake), ones on belts skip the ground checks, and all of them are
  stepped from one CargoTick instead of two Unity messages each.
- Belts leave a jammed line alone and only look every few steps whether it
  can move; splitters test distance before transforming every bundle.
- Light probes off on everything (the planet has none) and the GPU Resident
  Drawer off: both cost CPU per moving renderer for nothing.
- -demogpu N -onscreen measures frame time with one feature off at a time.

Base view 17-19 ms -> 14-15 ms, meadow 14-16 ms -> 11.5-12 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:01:02 +06:00

104 lines
5.7 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}");
if (CommandLine.Has("-tune"))
{
foreach (var r in FindObjectsByType<Renderer>(FindObjectsSortMode.None)) r.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off;
if (UnityEngine.Rendering.GraphicsSettings.currentRenderPipeline is UnityEngine.Rendering.Universal.UniversalRenderPipelineAsset ua) ua.gpuResidentDrawerMode = UnityEngine.Rendering.GPUResidentDrawerMode.Disabled;
outp.AppendLine("tuned: light probes off, resident drawer off");
}
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();
}
}
}