using System; using System.Diagnostics; namespace Swan.Diagnostics { public static partial class Benchmark { /// /// Represents a disposable benchmark unit. /// /// private sealed class BenchmarkUnit : IDisposable { private readonly string _identifier; private bool _isDisposed; // To detect redundant calls private Stopwatch? _stopwatch = new Stopwatch(); /// /// Initializes a new instance of the class. /// /// The identifier. public BenchmarkUnit(string identifier) { _identifier = identifier; _stopwatch?.Start(); } /// public void Dispose() => Dispose(true); /// /// Releases unmanaged and - optionally - managed resources. /// /// true to release both managed and unmanaged resources; false to release only unmanaged resources. private void Dispose(bool alsoManaged) { if (_isDisposed) return; if (alsoManaged) { Add(_identifier, _stopwatch?.Elapsed ?? default); _stopwatch?.Stop(); } _stopwatch = null; _isDisposed = true; } } } }