RaspberryIO_26/Swan.Lite/Diagnostics/BenchmarkUnit.cs
2019-12-08 19:54:52 +01:00

48 lines
1.5 KiB
C#

#nullable enable
using System;
using System.Diagnostics;
namespace Swan.Diagnostics {
public static partial class Benchmark {
/// <summary>
/// Represents a disposable benchmark unit.
/// </summary>
/// <seealso cref="IDisposable" />
private sealed class BenchmarkUnit : IDisposable {
private readonly String _identifier;
private Boolean _isDisposed; // To detect redundant calls
private Stopwatch? _stopwatch = new Stopwatch();
/// <summary>
/// Initializes a new instance of the <see cref="BenchmarkUnit" /> class.
/// </summary>
/// <param name="identifier">The identifier.</param>
public BenchmarkUnit(String identifier) {
this._identifier = identifier;
this._stopwatch?.Start();
}
/// <inheritdoc />
public void Dispose() => this.Dispose(true);
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="alsoManaged"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
private void Dispose(Boolean alsoManaged) {
if(this._isDisposed) {
return;
}
if(alsoManaged) {
Add(this._identifier, this._stopwatch?.Elapsed ?? default);
this._stopwatch?.Stop();
}
this._stopwatch = null;
this._isDisposed = true;
}
}
}
}