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.Concurrent;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Newtonsoft.Json.Linq;
using VRage.Render.Scene.Components;

namespace XFE.SeAgent.Plugin.Performance
{
    internal sealed class ActorMetrics
    {
        private sealed class Counter { public long Calls, Ticks; }
        private readonly ConcurrentDictionary<Type, Counter> types = new ConcurrentDictionary<Type, Counter>();
        public void Measure(MyActorComponent component, Action<MyActorComponent> action)
        {
            var counter = types.GetOrAdd(component.GetType(), _ => new Counter());
            long start = Stopwatch.GetTimestamp();
            try { action(component); }
            finally { Interlocked.Add(ref counter.Ticks, Stopwatch.GetTimestamp() - start); Interlocked.Increment(ref counter.Calls); }
        }
        public JArray Report() => new JArray(types.OrderByDescending(p => p.Value.Ticks).Select(p => new JObject {
            ["type"] = p.Key.FullName, ["calls"] = p.Value.Calls, ["totalMs"] = p.Value.Ticks * 1000.0 / Stopwatch.Frequency }));
    }
}