XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFE.SpaceEngineers.AgentBridge

【SpaceEngineer】AI调试插件

公开
关注 0 Fork 0 Star 0
UTF-8
using System;
using System.Collections.Generic;
using System.Linq;

namespace XFE.SeAgent.Plugin.Performance
{
    // A bounded series of wall-clock intervals, independent of the simulation clock.
    public sealed class FrameSeries
    {
        private readonly List<double> values = new List<double>(16384);
        private readonly object gate = new object();
        private double previous;
        private int dropped;
        public void Reset() { lock (gate) { values.Clear(); previous = 0; dropped = 0; } }
        public void Mark(double milliseconds)
        {
            lock (gate)
            {
                if (previous > 0 && milliseconds > previous)
                {
                    if (values.Count < 131072) values.Add(milliseconds - previous); else dropped++;
                }
                previous = milliseconds;
            }
        }
        public FrameSummary Summarize()
        {
            double[] sorted; int omitted;
            lock (gate) { sorted = values.ToArray(); omitted = dropped; }
            var ordered = (double[])sorted.Clone();
            Array.Sort(sorted);
            if (sorted.Length == 0) return new FrameSummary { Dropped = omitted };
            double mean = sorted.Average();
            int tail = Math.Max(1, (int)Math.Ceiling(sorted.Length * .01));
            double threshold = Math.Max(50, Percentile(sorted, .50) * 2), elapsed = 0;
            var longFrames = new List<LongFrame>(); int longCount = 0;
            for (int i = 0; i < ordered.Length; i++)
            {
                elapsed += ordered[i];
                if (ordered[i] < threshold) continue;
                longCount++;
                if (longFrames.Count < 256) longFrames.Add(new LongFrame { Index = i, EndMs = elapsed, DurationMs = ordered[i] });
            }
            return new FrameSummary { Count = sorted.Length, Dropped = omitted, MeanMs = mean, Fps = 1000 / mean,
                P50Ms = Percentile(sorted, .50), P95Ms = Percentile(sorted, .95), P99Ms = Percentile(sorted, .99),
                OnePercentLowFps = 1000 / sorted.Skip(sorted.Length - tail).Average(), MaxMs = sorted[sorted.Length - 1],
                LongFrameThresholdMs = threshold, LongFrameCount = longCount, LongFrames = longFrames.ToArray() };
        }
        private static double Percentile(double[] sorted, double p) => sorted[Math.Max(0, (int)Math.Ceiling(sorted.Length * p) - 1)];
    }
    public sealed class FrameSummary
    {
        public int Count, Dropped;
        public double Fps, MeanMs, P50Ms, P95Ms, P99Ms, OnePercentLowFps, MaxMs;
        public double LongFrameThresholdMs;
        public int LongFrameCount;
        public LongFrame[] LongFrames = new LongFrame[0];
    }
    public sealed class LongFrame { public int Index; public double EndMs, DurationMs; }
}