Skip to content

Instantly share code, notes, and snippets.

@Zabaa
Created August 25, 2019 19:01
Show Gist options
  • Save Zabaa/392cc83285d37e7bf1f23124334aafa1 to your computer and use it in GitHub Desktop.
Save Zabaa/392cc83285d37e7bf1f23124334aafa1 to your computer and use it in GitHub Desktop.
public static class DateTimeExtentions
{
public static string ToDateTimeHighPrecision(this DateTime source)
{
return source.ToString("MM/dd/yyyy h:mm:ss.fff tt");
}
}
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;
}
}
/// <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