Skip to content

Instantly share code, notes, and snippets.

@tkrotoff tkrotoff/ExecutionTimer.cs
Last active Dec 29, 2016

Embed
What would you like to do?
Simplifies the use of System.Diagnostics.Stopwatch
using System;
using System.Diagnostics;
/// <summary>
/// Simplifies the use of System.Diagnostics.Stopwatch.
/// </summary>
/// <example>
/// <code>
/// var timer1 = ExecutionTimer();
/// computeSomething();
/// timer1.StopAndDisplay(); // Debug output: "MyNamespace.MyClass.MyMethod: 00m 12s 263ms"
///
/// var timer2 = ExecutionTimer();
/// computeSomethingElse();
/// timer2.StopAndDisplay("computeSomethingElse"); // Debug output: "MyNamespace.MyClass.MyMethod computeSomethingElse: 00m 14s 499ms"
/// </code>
/// </example>
class ExecutionTimer {
private readonly Stopwatch _stopWatch;
public ExecutionTimer()
{
_stopWatch = new Stopwatch();
_stopWatch.Start();
}
public void StopAndDisplay(string info = null)
{
_stopWatch.Stop();
TimeSpan ts = _stopWatch.Elapsed;
string tmp = "";
if (!string.IsNullOrEmpty(info))
{
tmp = " " + info;
}
Debug.WriteLine(GetClassAndMethodName() + tmp + ": " + ts.ToString("mm'm 'ss's 'fff'ms'"));
}
private static string GetClassAndMethodName()
{
var stackTrace = new StackTrace();
var method = stackTrace.GetFrame(2).GetMethod();
string className = method.ReflectedType.FullName;
string methodName = method.Name;
methodName = methodName.Replace(".ctor", "ctor");
return className + "." + methodName;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.