using System.Collections.Generic; using System.Diagnostics; namespace Artemis.Core; /// /// Represents a profiler that can measure time between calls distinguished by identifiers /// public class Profiler { internal Profiler(Plugin plugin, string name) { Plugin = plugin; Name = name; } /// /// Gets the plugin this profiler belongs to /// public Plugin Plugin { get; } /// /// Gets the name of this profiler /// public string Name { get; } /// /// Gets a dictionary containing measurements by their identifiers /// public Dictionary Measurements { get; set; } = new(); /// /// Starts measuring time for the provided /// /// A unique identifier for this measurement public void StartMeasurement(string identifier) { lock (Measurements) { if (!Measurements.TryGetValue(identifier, out ProfilingMeasurement? measurement)) { measurement = new ProfilingMeasurement(identifier); Measurements.Add(identifier, measurement); } measurement.Start(); } } /// /// Stops measuring time for the provided /// /// A unique identifier for this measurement /// The number of ticks that passed since the call with the same identifier public long StopMeasurement(string identifier) { long lockRequestedAt = Stopwatch.GetTimestamp(); lock (Measurements) { if (!Measurements.TryGetValue(identifier, out ProfilingMeasurement? measurement)) { measurement = new ProfilingMeasurement(identifier); Measurements.Add(identifier, measurement); } return measurement.Stop(Stopwatch.GetTimestamp() - lockRequestedAt); } } /// /// Clears measurements with the the provided /// /// public void ClearMeasurements(string identifier) { lock (Measurements) { Measurements.Remove(identifier); } } }