Created
August 25, 2019 19:01
-
-
Save Zabaa/392cc83285d37e7bf1f23124334aafa1 to your computer and use it in GitHub Desktop.
Gist based on Lance Larsen article http://lancelarsen.com/stopwatchlog-easy-method-timing-in-c/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class DateTimeExtentions | |
{ | |
public static string ToDateTimeHighPrecision(this DateTime source) | |
{ | |
return source.ToString("MM/dd/yyyy h:mm:ss.fff tt"); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public struct Measurement | |
{ | |
public string Text { get; set; } | |
public long ElapsedMilliseconds { get; set; } | |
public DateTime Time { get; set; } | |
public Measurement(string text, DateTime time, long elapsedMilliseconds) | |
{ | |
Text = text; | |
ElapsedMilliseconds = elapsedMilliseconds; | |
Time = time; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Collects information about executing method and logs metrics | |
/// when the stopwatch log is disposed. | |
/// </summary> | |
/// <example> | |
/// using (StopwatchLog.Track()) | |
/// { | |
/// // Code here... | |
/// } | |
/// </example> | |
public sealed class StopwatchLog : IDisposable | |
{ | |
public string Text { get; set; } | |
public Stopwatch Stopwatch { get; set; } | |
public DateTime StopwatchStart { get; set; } | |
public DateTime StopwatchStop { get; set; } | |
public List<Measurement> Measurements { get; set; } = new List<Measurement>(); | |
private StopwatchLog(string text) | |
{ | |
Text = text; | |
StopwatchStart = DateTime.UtcNow; | |
Stopwatch = Stopwatch.StartNew(); | |
} | |
void IDisposable.Dispose() | |
{ | |
Stopwatch.Stop(); | |
StopwatchStop = DateTime.UtcNow; | |
LogMetrics(); | |
} | |
private void LogMetrics() | |
{ | |
Console.WriteLine("{0} | Started: {1} | Ended {2} | Elapsed {3} ms", | |
Text, | |
StopwatchStart.ToDateTimeHighPrecision(), | |
StopwatchStop.ToDateTimeHighPrecision(), | |
Stopwatch.ElapsedMilliseconds); | |
} | |
public static StopwatchLog Track(string text) | |
{ | |
return new StopwatchLog(text); | |
} | |
public void Measure(string text) | |
{ | |
Measurements.Add(new Measurement(text, DateTime.UtcNow, Stopwatch.ElapsedMilliseconds)); | |
Stopwatch.Restart(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment