Measure time elapsed
public class TimeRuler { private readonly Stopwatch stopWatch = new Stopwatch(); private readonly StringBuilder stringBuilder = new StringBuilder(); private long _prevMeasure = 0; private string currentDescription; public TimeRuler(bool start = true) { if (start) stopWatch.Start(); } public void Measure(string description) { var measure = stopWatch.ElapsedMilliseconds; var added = measure - _prevMeasure; _prevMeasure = measure; stringBuilder.AppendLine($"{measure,12} {added,12} + {description}"); } public void Start(string description) { currentDescription = description; Measure($"Start: {description}"); } public void End() => Measure($"End: {currentDescription}"); public override string ToString() => stringBuilder.ToString(); }
using System; using System.Diagnostics; using System.Text; namespace Domain.Helpers { public class TimeRuler : IDisposable { private Stopwatch stopWatch = new Stopwatch(); private StringBuilder stringBuilder = new StringBuilder(); private long _prevMeasure = 0; public TimeRuler(bool start = true) { if (start) stopWatch.Start(); } public void Measure(string description) { var measure = stopWatch.ElapsedMilliseconds; var added = measure - _prevMeasure; _prevMeasure = measure; stringBuilder.AppendLine($"{measure,12} {added,12} + {description}"); } public override string ToString() { return stringBuilder.ToString(); } #region IDisposable Support private bool disposedValue = false; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { if (stopWatch.IsRunning) stopWatch.Stop(); stopWatch = null; } disposedValue = true; } } public void Dispose() { Dispose(true); } #endregion } }
using (var timeRuler = new TimeRuler()) { timeRuler.Measure("A"); Calculate1(); timeRuler.Measure("B"); Calculate2(); timeRuler.Measure("C"); Console.WriteLine(timeRuler.ToString()) }
331300cookie-checkC# TimeRuler